0% found this document useful (0 votes)
15 views29 pages

Answer Assessment - Java Full Stack

Answer Assessment - Java full stack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views29 pages

Answer Assessment - Java Full Stack

Answer Assessment - Java full stack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MODULE 1

1. Which of the following is not a feature of Java?


c) Operator Overloading
2. Which keyword is used to inherit a class in Java?
c) extends
3. Which of the following is a valid data type in Java?
b) float
4. Which is the default value of a local variable in Java?
d) No default value
5. Which control statement is used to exit a loop early in Java?
c) break
6. Which loop is guaranteed to execute at least once?
c) do-while loop
7. Which of the following correctly declares an array of 5 integers?
b) int arr[] = new int[5];
8. Which method is used to get the length of a string in Java?
d) length()
9. Which exception is thrown when dividing a number by zero?
b) ArithmeticException
10. Which keyword is used to handle exceptions in Java?
c) catch
11. Which of these classes implements a dynamic array in Java?
b) ArrayList
12. Which interface must a class implement to use threads in Java?
a) Runnable
13. Which method is used to start a thread?
b) start()
14. Which class is used for reading bytes from a file?
c) FileInputStream
15. Which class is used for reading character data from a file?
a) FileReader

1
16. What is the purpose of the Optional class introduced in Java 8?
c) To avoid NullPointerException
17. Which of the following is not a functional interface in Java 8?
d) String
18. What does a lambda expression return?
c) Interface implementation
19. Which operation is a terminal operation in the Java 8 Streams API?
c) forEach()
20. Which keyword is used to define a method with default implementation in an interface?
c) default

Example Programs

1. Check Even or Odd

import [Link];

public class EvenOdd {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");

int num = [Link]();

if (num % 2 == 0)

[Link](num + " is Even");

else

[Link](num + " is Odd");

Output:

2
Enter a number: 7

7 is Odd

2. Factorial Using Loop

import [Link];

public class Factorial {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");

int num = [Link]();

long fact = 1;

for (int i = 1; i <= num; i++) {

fact *= i;

[Link]("Factorial: " + fact);

Output:

Enter a number: 5

Factorial: 120

3. Palindrome String Check

import [Link];

public class Palindrome {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

3
String str = [Link]();

String reversed = "";

for (int i = [Link]() - 1; i >= 0; i--) {

reversed += [Link](i);

if ([Link](reversed))

[Link]("Palindrome");

else

[Link]("Not Palindrome");

Output:

Enter a string: madam

Palindrome

4. Find Largest and Smallest in Array

public class ArrayMinMax {

public static void main(String[] args) {

int[] arr = {4, 10, 3, 25, 7};

int min = arr[0], max = arr[0];

for (int num : arr) {

if (num < min) min = num;

if (num > max) max = num;

[Link]("Smallest: " + min);

[Link]("Largest: " + max);

4
}

Output:

Smallest: 3

Largest: 25

5. Count Vowels and Consonants

import [Link];

public class VowelConsonantCount {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

String str = [Link]().toLowerCase();

int vowels = 0, consonants = 0;

for (char ch : [Link]()) {

if ([Link](ch)) {

if ("aeiou".indexOf(ch) != -1)

vowels++;

else

consonants++;

[Link]("Vowels: " + vowels);

[Link]("Consonants: " + consonants);

5
Output:

Enter a string: Hello World

Vowels: 3

Consonants: 7

6. Employee Class and Object

class Employee {

String name;

int id;

double salary;

Employee(String name, int id, double salary) {

[Link] = name;

[Link] = id;

[Link] = salary;

void display() {

[Link]("Name: " + name);

[Link]("ID: " + id);

[Link]("Salary: $" + salary);

public class EmployeeDemo {

public static void main(String[] args) {

Employee emp = new Employee("Alice", 101, 50000);

[Link]();

6
}

Output:

Name: Alice

ID: 101

Salary: $50000.0

7. Exception Handling (Divide by Zero)

public class ExceptionHandling {

public static void main(String[] args) {

try {

int result = 10 / 0;

} catch (ArithmeticException e) {

[Link]("Error: Cannot divide by zero.");

Output:

Error: Cannot divide by zero.

8. FileReader & FileWriter Example

import [Link].*;

public class FileReadWrite {

public static void main(String[] args) {

try {

FileWriter writer = new FileWriter("[Link]");

[Link]("Java File Handling Example");

[Link]();

7
FileReader reader = new FileReader("[Link]");

int ch;

[Link]("File Content: ");

while ((ch = [Link]()) != -1) {

[Link]((char) ch);

[Link]();

} catch (IOException e) {

[Link]("File Error: " + [Link]());

Output:

File Content: Java File Handling Example

9. Thread to Print Numbers with Delay

class NumberPrinter extends Thread {

public void run() {

for (int i = 1; i <= 10; i++) {

[Link](i);

try {

[Link](1000); // 1 second delay

} catch (InterruptedException e) {

[Link](e);

8
}

public class ThreadExample {

public static void main(String[] args) {

NumberPrinter np = new NumberPrinter();

[Link]();

Output: (1 number per second)

...

10

10. Java 8 – Stream API Filter Example

import [Link];

import [Link];

public class StreamFilter {

public static void main(String[] args) {

List<String> names = [Link]("Sam", "John", "Sita", "Alex", "Steve");

[Link]()

.filter(name -> [Link]("S"))

.forEach([Link]::println);

9
Output:

Sam

Sita

Steve

10
MODULE 2

1. C. Statement

2. B. Type-1 Driver

3. C. [Link]()

4. B. PreparedStatement

5. C. Call stored procedures

6. C. [Link]()

7. C. Handles user input and logic

8. C. Directive

9. D. scanner

10. C. <%= x + 1 %>

11. B. <%@ include %>

12. C. jspInit()

13. A. JSTL

14. C. session

15. C. A no-arg constructor and getter/setter methods

16. C. @WebFilter

17. B. HttpSessionListener

18. C. application

19. C. JSPs mix HTML with Java, Servlets separate them

20. C. To track user data across multiple requests

1. import [Link].*;

11
public class JDBCInsertExample {

public static void main(String[] args) {

try {

[Link]("[Link]");

Connection con =

[Link]("jdbc:mysql://localhost:3306/testdb", "root", "password");

String query = "INSERT INTO students (name, age) VALUES (?, ?)";

PreparedStatement pst = [Link](query);

[Link](1, "John");

[Link](2, 20);

int rows = [Link]();

[Link](rows + " row(s) inserted.");

[Link]();

} catch (Exception e) {

[Link]();

12
}

2. import [Link].*;

import [Link].*;

import [Link].*;

public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<h1>Hello, World from Servlet!</h1>");

3. <%@ page language="java" %>

<html>

<head><title>Welcome</title></head>

<body>

<h1>Welcome to JSP Programming</h1>

</body>

13
</html>

4. Model

public class User {

private String username;

private String password;

// Getters and setters

View

<form action="LoginController" method="post">

Username: <input name="username" /><br/>

Password: <input type="password" name="password" /><br/>

<input type="submit" value="Login"/>

</form>

Controller

import [Link].*;

import [Link].*;

import [Link].*;

14
public class LoginController extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws

IOException, ServletException {

String user = [Link]("username");

String pass = [Link]("password");

if([Link]("admin") && [Link]("admin123")) {

[Link]("[Link]");

} else {

[Link]("[Link]");

5. JSP Page to Set Session:

<%

String name = [Link]("username");

[Link]("user", name);

%>

15
<a href="[Link]">Go to Welcome Page</a>

[Link]

<%

String user = (String) [Link]("user");

%>

<h1>Welcome, <%= user %></h1>

16
MODULE 3

HTML5 & CSS3

1. Which HTML5 tag is used to define a container for navigation links?

b) <nav>

2. Which of the following CSS3 properties is used to create rounded corners?

c) border-radius

JavaScript (ES6+)

3. What is the output of the following code?

let x = [1, 2, 3];

let y = [...x];

[Link](4);

[Link](x);

b) [1, 2, 3]

Because the spread operator (...) creates a shallow copy of the array.

4. What does the const keyword do in JavaScript?

b) Declares a constant that cannot be changed or reassigned

Bootstrap

5. Which Bootstrap class is used to make a button block-level and full-width?

a) .btn-block

6. What is the default grid system in Bootstrap 4 based on?

b) 12 columns

TypeScript

7. What is the purpose of TypeScript?

b) To define types and catch errors during development

8. Which of the following is a correct way to declare a variable with a type in TypeScript?

17
a) let age: number = 25;

[Link]

9. Which hook is used to manage state in a functional component in React?

a) useState()

10. What are props in React?

c) Arguments passed to components from parent

Samples

1. Write a program using JavaScript ES6 features (e.g., arrow functions, spread
operator) to find the largest number in an array.
const numbers = [45, 67, 89, 23, 91, 12];
const findMax = arr => [Link](...arr);
[Link]("Max:", findMax(numbers));
Output:
Max: 91
2. Design a responsive 3-column layout using Bootstrap and HTML5 where each
column contains a card with a title and a paragraph.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Grid</title>
<link rel="stylesheet"
href="[Link]
</head>
<body>
<div class="container mt-4">
<div class="row">
<div class="col-md-4">
<div class="card p-3">
<h4>Card 1</h4>

18
<p>This is content for card one.</p>
</div>
</div>
<div class="col-md-4">
<div class="card p-3">
<h4>Card 2</h4>
<p>This is content for card two.</p>
</div>
</div>
<div class="col-md-4">
<div class="card p-3">
<h4>Card 3</h4>
<p>This is content for card three.</p>
</div>
</div>
</div>
</div>
</body>
</html>
3. Write a TypeScript program that defines a function to add two numbers. Ensure
type safety.
function add(a: number, b: number): number {
return a + b;
}
[Link]("Sum:", add(15, 30));
Output:
Sum: 45
4. Build a simple counter component using React functional components and the
useState hook.
import React, { useState } from 'react';
function Counter() {

19
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
5. Fetch and display a single user’s name and email using Fetch API from
JSONPlaceholder.
<!DOCTYPE html>
<html>
<body>
<h3>User Info</h3>
<div id="user"></div>
<script>
fetch("[Link]
.then(res => [Link]())
.then(user => {
[Link]("user").innerHTML =
`<strong>Name:</strong> ${[Link]}<br><strong>Email:</strong> $
{[Link]}`;
})
.catch(err => [Link]("Fetch error:", err));
</script>
</body>
</html>

Output:

Name: Leanne Graham

20
Email: Sincere@[Link]

21
MODULE 4

MCQ

RDBMS Concepts

a) Relational Database Management System

c) Data stored in hierarchical structure

b) Uniquely identify each record in a table

b) A field in one table that refers to the primary key in another table

c) NOT NULL

a) Atomicity

a) Data redundancy

c) ER (Entity-Relationship) model

MySQL / PostgreSQL

b) MySQL Workbench

d) TEXT

b) Object-relational database

a) CREATE USER

c) Both

b) 3306

a) pg_dump

Database Design and Normalization

b) Reduce data redundancy and improve integrity

a) 1NF

b) Some columns depend only on part of the composite key

c) 3NF

22
a) Improve query performance by introducing redundancy

c) Relationship

c) A junction (bridge) table

SQL Queries and Joins

a) SELECT

a) WHERE

c) Rows that have matching values in both tables

b) LEFT JOIN

c) Cartesian product of two tables (CROSS JOIN)

a) ORDER BY

b) HAVING

c) TRUNCATE table_name;

Sample Program Answer

1. Create and populate a table

SQL Query:

CREATE TABLE Students (

StudentID INT PRIMARY KEY,

Name VARCHAR(50),

Age INT,

Class VARCHAR(20)

);

INSERT INTO Students (StudentID, Name, Age, Class) VALUES

(1, 'Alice', 16, '10th Grade'),

(2, 'Bob', 17, '11th Grade'),

(3, 'Charlie', 15, '10th Grade'),

23
(4, 'David', 18, '12th Grade'),

(5, 'Eve', 16, '11th Grade');

2. Retrieve data with condition

SQL Query:

SELECT * FROM Students WHERE Age > 15;

Output:

This will show all students older than 15 years (Alice, Bob, David, Eve).

3. Update records

SQL Query:

UPDATE Students

SET Class = '12th Grade'

WHERE StudentID = 2;

Explanation:

This updates Bob’s class from "11th Grade" to "12th Grade".

4. Perform an INNER JOIN

Assuming Grades table:

CREATE TABLE Grades (

StudentID INT,

Subject VARCHAR(50),

Grade CHAR(2),

FOREIGN KEY (StudentID) REFERENCES Students(StudentID)

);

INSERT INTO Grades (StudentID, Subject, Grade) VALUES

(1, 'Math', 'A'),

(2, 'Math', 'B'),

24
(3, 'Science', 'A'),

(4, 'English', 'C'),

(5, 'Science', 'B');

SQL INNER JOIN Query:

SELECT [Link], [Link], [Link]

FROM Students

INNER JOIN Grades ON [Link] = [Link];

Output:

List of student names with their subjects and grades.

5. Java JDBC connection and query

import [Link].*;

public class RetrieveStudents {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/School"; // Change port/db as needed

String user = "root"; // your DB username

String password = "password"; // your DB password

try {

// Load the JDBC driver (optional for newer versions)

[Link]("[Link]");

// Establish connection

Connection conn = [Link](url, user, password);

// Create statement and execute query

25
Statement stmt = [Link]();

String sql = "SELECT * FROM Students";

ResultSet rs = [Link](sql);

// Process results

while ([Link]()) {

int id = [Link]("StudentID");

String name = [Link]("Name");

int age = [Link]("Age");

String cls = [Link]("Class");

[Link](id + "\t" + name + "\t" + age + "\t" + cls);

// Close connections

[Link]();

[Link]();

[Link]();

} catch (Exception e) {

[Link]();

26
MODULE 5

MCQ

1. D. Dependency Injection
2. C. Constructor Injection
3. C. SessionContext
4. C. @RequestMapping
5. A. String
6. C. @RestController
7. B. [Link].
8. B. Tomcat
9. D. @SpringBootApplication
10. B. JpaRepository
11. B. @Query
12. C. SecurityFilterChain
13. C. BCryptPasswordEncoder
14. C. PUT
15. B. 201 Created
Program Samples

1. [Link]

public interface Vehicle {

void move();

[Link]

public class Car implements Vehicle {

public void move() {

[Link]("Car is moving...");

27
}

[Link]

public class Bike implements Vehicle {

public void move() {

[Link]("Bike is moving...");

[Link]

public class Travel {

private Vehicle vehicle;

public Travel(Vehicle vehicle) {

[Link] = vehicle;

public void startJourney() {

[Link]();

[Link]

import [Link];

import [Link];

@Configuration

public class AppConfig {

@Bean

28
public Vehicle vehicle() {

return new Car(); // Change to new Bike() to use Bike

@Bean

public Travel travel() {

return new Travel(vehicle());

[Link]

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext([Link]);

Travel travel = [Link]([Link]);

[Link]();

29

You might also like