0% found this document useful (0 votes)
20 views126 pages

Java Mycompetency Final

The document contains a series of Java-related questions and answers covering topics such as JMS message consumption, thread behavior, HTTP requests, lambda expressions, and Java 9 features. Each question includes options and explanations for the correct answers, providing insights into Java programming concepts. The questions range from basic syntax and behavior to more advanced topics like EJB and functional programming.

Uploaded by

DM CUTZ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views126 pages

Java Mycompetency Final

The document contains a series of Java-related questions and answers covering topics such as JMS message consumption, thread behavior, HTTP requests, lambda expressions, and Java 9 features. Each question includes options and explanations for the correct answers, providing insights into Java programming concepts. The questions range from basic syntax and behavior to more advanced topics like EJB and functional programming.

Uploaded by

DM CUTZ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Question 0 (JMS Message Consumption)

Question: The following is a JMS code for a consumer in ActiveMQ. Which of the following code snippet should be inserted
in the specified section of the code below to complete the consumer class? (The context suggests inserting code to
establish connection or message reception.)

Code Snippet (Partial):

Java
//CODE TO ESTABLISH CONNECTION (from page 25)

Session session = [Link](false,


Session.AUTO_ACKNOWLEDGE);
Destination destination = [Link]("[Link]"); // Assuming from context on page 5
//INSERT CODE HERE

Options (from pages 1, 3, 21):

Java
MessageConsumer consumer = [Link] (destination); [cite: 35, 23]
TextMessage message = [Link](1000); [cite: 35, 23]
if (message instanceof Message) ( // Note: 'Message' here should likely be 'TextMessage' based on the casting and
getText() call, but in the provided code, it uses 'Message' [cite: 36, 25]
Message textMessage = (Message) message; [cite: 36, 25]
String text = [Link](); [cite: 25]
[Link]("Received: " + text); [cite: 25]
} else {
[Link]("Received: " + message); [cite: 25]
}
[Link](); [cite: 26]

Answer: The correct insertion for //INSERT CODE HERE to complete a synchronous message reception logic would be:

Java
MessageConsumer consumer = [Link] (destination);
TextMessage message = [Link](1000);
// Followed by logic to process the message like:
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
String text = [Link]();
[Link]("Received: " + text);
}

Note: The question is likely asking for the code to create the consumer and receive the message. The provided snippets
(pages 1, 3, 21) show a complete synchronous consumer logic.

Explanation:

1. Create Consumer: MessageConsumer consumer = [Link](destination); creates an object to


receive messages from the specified destination (Queue or Topic).
2. Receive Message: [Link](1000); attempts to receive a message synchronously, blocking for up to
1000 milliseconds.

Question 1

What will be the outcome when the given code is compiled and run?
class Test27 {

public static void main(String as[]) {

[Link](0.0 % 0.0 != 0.0 / 0.0);

Options:

1. true

1. compilation error

1. false

1. NaN

Correct Answer: A) true


Explanation:
Both 0.0 % 0.0 and 0.0 / 0.0 result in NaN. In Java, NaN != NaN evaluates to true.
Note: NaN comparisons are tricky — NaN == NaN is false, NaN != NaN is true.

Question 2

Predict the output of the following code:

class MyThread extends Thread {

MyThread() {}

MyThread(Runnable r) {

super(r);

public void run() {

[Link]("Inside Thread ");

class MyRunnable implements Runnable {

public void run() {

[Link](" Inside Runnable");

} class Test {

public static void main(String[] args) {

new MyThread().start();

new MyThread(new MyRunnable()).start();

Options:
1. Prints "Inside Thread Inside Thread"

1. Prints "Inside Thread Inside Runnable"

1. Compilation Fails

1. Runtime Exception

Correct Answer: A) Prints "Inside Thread Inside Thread"


Explanation:
Even though the second thread is passed a Runnable, the run() method is overridden in MyThread, so both threads execute
[Link]().
Note: To invoke the Runnable’s run(), you must not override run() in the subclass or explicitly call [Link]().

Question 3

If we try to invoke start() method on a dead thread, then what happens?

Options:

1. Thread will become Runnable again

1. Thread will become Running again

1. Thread will not come alive again but the program will not throw any exception

1. Runtime exception will occur

Correct Answer: D) Runtime exception will occur


Explanation:
Calling start() on a thread that has already been started throws IllegalThreadStateException.
Note: A thread can only be started once.

Question 4

For the URL [Link] which HTTP request gets generated?

Options:

1. GET

1. POST

1. HEAD

1. PUT

Correct Answer: A) GET


Explanation:
Accessing a URL via browser defaults to a GET request.
Note: POST is used when submitting forms.

Question 5

Which object is used to access web services via browsers?

Options:

1. XmlHttpRequest

1. SmlHttpRequest

1. JSONP

1. WebSocket
Correct Answer: A) XmlHttpRequest
Explanation:
XmlHttpRequest is the standard JavaScript object for AJAX calls.
Note: JSONP is a workaround for cross-domain requests, not a direct API.

Question 6

What is the type of a lambda expression?

Options:

1. Object

1. Class

1. Depends on the context where lambda expression is used

1. Some generic type

Correct Answer: C) Depends on the context where lambda expression is used


Explanation:
Lambda expressions are treated as instances of functional interfaces, and their type is inferred from the context.
Note: They don’t have a concrete class type.

Question 7

Which method was introduced in Java 8 to iterate over a collection?

Options:

1. iterator() method in Iterable interface

1. forEach() method in Iterable interface

1. for() method in List interface

1. iterator() method in List interface

Correct Answer: B) forEach() method in Iterable interface


Explanation:
Java 8 added forEach() as a default method to Iterable.
Note: Enables functional-style iteration.

Question 8

What does [Link]("Query").scroll() return?

Options:

1. ListResultSet

1. ResultSet

1. ScrollableResultSet

1. ScrollableResult

Correct Answer: D) ScrollableResult


Explanation:
In Hibernate, scroll() returns a ScrollableResults object (often referred to as ScrollableResult in exams).
Note: Useful for large datasets with cursor-like navigation.

Question 9

What is the output of the following code?


class Test {

public static void main(String args[]) {

Thread t = [Link]();

[Link](t);

Options:

1. Compile time error

1. Runtime error

1. Thread[main,5,main]

1. Thread[main,5]

Correct Answer: C) Thread[main,5,main]


Explanation:
[Link]() returns the thread name, priority, and group.
Note: Output format may vary slightly by JVM.

Question 10

If a HashMap contains serializable objects, which statement is true?

Options:

1. HashMap can be passed as an argument to a remote method call.

1. HashMap cannot be passed as an argument to remote method call.

1. HashMap cannot contain serializable objects.

1. None of the given options

Correct Answer: A) HashMap can be passed as an argument to a remote method call.


Explanation:
As long as all keys and values are serializable, the HashMap itself can be serialized and passed remotely.
Note: RMI requires all transmitted objects to be serializable.

Would you like me to continue with the next batch? I can keep going until all questions are covered. Let me know if you
want any tweaks to the format too!

Question 11

What would happen if we directly call the run() method of a thread instead of start()?

class Multi extends Thread {

public void run() {

[Link]("running");

public static void main(String args[]) {


Multi t1 = new Multi();

[Link](); // Direct call

Options:

1. It is compile time error as we extend our class by thread class

1. It will run normally and print "running"

1. Compile time error as we did not call start() method of thread

1. Runtime error

Correct Answer: B) It will run normally and print "running"


Explanation:
Calling run() directly executes the method like any other method — it does not start a new thread.
Note: To run in a separate thread, use start().

Question 12

What is the output of the following code?

public class Test {

public static void main(String[] args) {

try {

return;

} catch(Exception e) {

[Link]("catch");

} finally {

[Link]("finally");

Options:

1. catch

1. finally

1. nothing

1. compile time error

Correct Answer: B) finally


Explanation:
Even if return is called in try, the finally block always executes.
Note: finally is guaranteed to run regardless of return, break, or continue.

Question 13

Which method was added to Map in Java 9?


Options:

1. static Map of(K k1, V v1, K k2, V v2, K k3, V v3)

1. Map ofMap(K k1, V v1, K k2, V v2, K k3, V v3)

1. Both Option 1 and 2

1. None

Correct Answer: A) static Map of(...)


Explanation:
Java 9 introduced [Link]() to create immutable maps.
Note: [Link]() does not exist.

Question 14

Which of the following is NOT a correct signature for method overloading of void fun()?

Options:

1. void fun(int a)

1. int fun(int a)

1. void fun(int a, int b)

1. All of the above

Correct Answer: D) All of the above


Explanation:
All listed signatures are valid overloads of void fun() because they differ in parameters or return type.
Note: Overloading requires different parameter lists — return type alone is not enough.

Question 15

What is the output of the following code?

public class Test {

public static void main(String[] args) {

try {

return;

} catch(Exception e) {

[Link]("catch");

} finally {

[Link]("finally");

Options:

1. catch

1. finally

1. nothing
1. compile time error

Correct Answer: B) finally


Explanation:
Even if return is executed, finally still runs.
Note: finally is always executed unless JVM exits or thread is killed.

Question 16

Which of the following is true about ActiveMQ?

Options:

1. Using ActiveMQ we can schedule our message to be delivered at a particular time.

1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue.

1. Messaging service in MQ works in FIFO (First In First Out) manner.

1. The "update" keyword is used in queries while using JMS like ApacheMessage Queue.

Correct Answer: A) Using ActiveMQ we can schedule our message to be delivered at a particular time.
Explanation:
ActiveMQ supports scheduled delivery using message properties like AMQ_SCHEDULED_DELAY.
Note: "update" is not a JMS keyword.

Question 17

Which of the following is NOT a valid HTTP request method?

Options:

1. put()

1. head()

1. delete()

1. resume()

Correct Answer: D) resume()


Explanation:
resume() is not a standard HTTP method.
Note: Valid methods include GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH.

Question 18

What is the output of the following Java code?

class q33 {

public static void main(String as[]) {

float f[] = new float[5];

Object obj = f;

[Link](f[0]);

Options:

1. Compilation Error
1. Runtime Exception

1. 0.0

1. 0

Correct Answer: C) 0.0


Explanation:
Default value for float array elements is 0.0f.
Note: Arrays of primitives are initialized with default values.

Question 19

Which one of the following could be closest to the key reason for including lambda expressions in JDK 8?

Options:

1. Support parallel bulk operations for collections

1. Make the Java programming language look more like a functional programming language

1. Introduce the functional programming paradigm in Java

1. Provide an alternative to usage of anonymous inner classes

Correct Answer: C) Introduce the functional programming paradigm in Java


Explanation:
Lambda expressions enable functional-style programming and simplify code.
Note: They also reduce boilerplate for anonymous classes.

Question 20

Select the correct option for the following code snippet:

[Link] r = () -> {

[Link]("This code will run");

};

Options:

1. Code will encounter compilation error

1. Code will throw exception

1. Code will run and print "This code will run" on console

Correct Answer: C) Code will run and print "This code will run" on console
Explanation:
This is a valid lambda expression implementing Runnable.

Question 21

What is the output of the following code?

public class Test {

public static void main(String[] args) throws Exception {

try {

int i = 5 / 0;

} catch(Exception e) {

throw new Exception();


} finally {

[Link]("In Finally");

Options:

1. Compilation Fails

1. Runtime Exception with no output

1. "In Finally" will be printed and no exception will be thrown

1. "In Finally" will be printed and a Runtime Exception will be thrown

Correct Answer: D) "In Finally" will be printed and a Runtime Exception will be thrown
Explanation:
Division by zero throws ArithmeticException, which is caught and rethrown as a new Exception. The finally block executes
regardless, printing "In Finally".
Note: The program terminates with an exception after printing.

Question 22

Which of the following annotations are used in EJB to define a session bean?

@Stateless

@Remote

@Local

public class WageBean implements Wage {

public float calculateWage() { /* logic */ }

public float calculateTax() { /* logic */ }

Options:

1. The given code is correct

1. The annotations should be on new lines

1. A bean cannot be defined as @Remote and @Local both

1. A bean cannot be defined as @Stateless or @Local

Correct Answer: A) The given code is correct


Explanation:
EJB allows a bean to be both @Remote and @Local if it implements both interfaces.
Note: Annotation placement on the same line is syntactically valid.

Question 23

Which of the following method is added to Map in Java 9?

Options:

1. static Map of(K k1, V v1, K k2, V v2, K k3, V v3)


1. Map ofMap(K k1, V v1, K k2, V v2, K k3, V v3)

1. Both Option 1 and 2

1. None

Correct Answer: A) static Map of(...)


Explanation:
Java 9 introduced [Link]() to create immutable maps.
Note: [Link]() is not a valid method.

Question 24

What is the use of abstract-schema-name entry in a CMP 2.0 entity bean's deployment descriptor?

Options:

1. It indicates the name of the bean class in the application's schema

1. It specifies the table in the database that will contain the persistent state

1. It specifies the schema identifier that will be used in the EJB-QL

1. None of the given options

Correct Answer: C) It specifies the schema identifier that will be used in the EJB-QL
Explanation:
abstract-schema-name is used to refer to the entity bean in EJB QL queries.
Note: It’s not the actual table name.

Question 25

Which of the following are valid JSP lifecycle methods?

Options:

1. jspInit()

1. jspLoad()

1. jspGet()

1. jspPost()

Correct Answer: A) jspInit()


Explanation:
jspInit() is called when the JSP is initialized.
Note: jspLoad(), jspGet(), and jspPost() are not valid JSP lifecycle methods.

Question 26

Which of the following is NOT a correct signature for method overloading of void fun()?

Options:

1. void fun(int a)

1. int fun(int a)

1. void fun(int a, int b)

1. All of the above

Correct Answer: D) All of the above


Explanation:
All listed signatures are valid overloads of void fun() because they differ in parameters or return type.
Note: Overloading requires different parameter lists — return type alone is not enough.

Question 27

Which of the following is NOT true about ActiveMQ?

Options:

1. Using ActiveMQ we can schedule our message to be delivered at a particular time

1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue

1. Messaging service in MQ works in FIFO (First In First Out) manner

1. The "update" keyword is used in queries while using JMS like ApacheMessage Queue

Correct Answer: D) The "update" keyword is used in queries while using JMS like ApacheMessage Queue
Explanation:
JMS does not use SQL-like keywords such as "update".
Note: ActiveMQ supports scheduling and FIFO delivery.

Question 28

Which of the following is NOT a valid HTTP request method?

Options:

1. put()

1. head()

1. delete()

1. resume()

Correct Answer: D) resume()


Explanation:
resume() is not a standard HTTP method.
Note: Valid methods include GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH.

Question 29

What is the output of the following Java code?

class q33 {

public static void main(String as[]) {

float f[] = new float[5];

Object obj = f;

[Link](f[0]);

Options:

1. Compilation Error

1. Runtime Exception

1. 0.0
1. 0

Correct Answer: C) 0.0


Explanation:
Default value for float array elements is 0.0f.
Note: Arrays of primitives are initialized with default values.

Question 30

Which of the following is the correct way to configure ActiveMQ to use both TCP and UDP transports on different ports?

Options:

<transportConnectors>

<transportConnector name="tcp" uri="tcp://localhost?trace=true" port="61616"/>

<transportConnector name="udp" uri="udp://localhost?trace=true" port="61618"/>

</transportConnectors>

<transportConnectors>

<transportConnector id="1" name="tcp" uri="tcp://localhost:61616?trace=true"/>

<transportConnector id="2" name="udp" uri="udp://localhost:61618?trace=true"/>

</transportConnector>

</transportConnectors>

Correct Answer: A)
Explanation:
Correct configuration uses name, uri, and port attributes inside transportConnector.
Note: Option B has malformed XML structure.

Let me know when you're ready for the next batch — I’ll keep going until every question is covered!

Question 31

Which of the following HTTP request methods is generated when accessing this URL?
[Link]

Options:

1. GET

1. POST

1. HEAD

1. PUT

Correct Answer: A) GET


Explanation:
Accessing a URL directly via browser generates a GET request.
Note: POST is used when submitting forms.

Question 32

Which of the following object is used to access web services via browsers?
Options:

1. XmlHttpRequest

1. SmlHttpRequest

1. JSONP

1. WebSocket

Correct Answer: A) XmlHttpRequest


Explanation:
XmlHttpRequest is the standard JavaScript object used for AJAX calls.
Note: JSONP is a workaround for cross-domain requests, not a direct API.

Question 33

class Test {

public static void main(String args[]) {

Thread t = [Link]();

[Link](t);

What is the output of the following code?

class Test { public static void main(String args[]) { Thread t = [Link](); [Link](t); } }

Options:

1. Compile time error

1. Runtime error

1. Thread[main,5,main]

1. Thread[main,5]

Correct Answer: C) Thread[main,5,main]


Explanation:
[Link]() returns the thread name, priority, and group.
Note: Output format may vary slightly by JVM.

Question 34

What would be the output of the following program?

import [Link];

import [Link];

import [Link];

class Test {

public static void main(String[] args) {

HashMap t = new HashMap();

[Link](null, 1);
[Link](3, 2);

Set s = [Link]();

Iterator iter = [Link]();

while([Link]()) {

[Link]([Link]());

Options:

1. 3

1. null 3

1. [Link] at runtime

1. null

Correct Answer: B) null 3


Explanation:
HashMap allows one null key. The iteration order is not guaranteed, but both keys will be printed.
Note: No exception is thrown for null key in HashMap.

Question 35

What is the output of the following code?

public class Test {

public static void main(String[] args) {

try {

return;

} catch(Exception e) {

[Link]("catch");

} finally {

[Link]("finally");

Options:

1. catch

1. finally

1. nothing

1. compile time error


Correct Answer: B) finally
Explanation:
Even if return is executed, finally still runs.
Note: finally is always executed unless JVM exits or thread is killed.

Question 36

Which of the following is NOT a correct signature for method overloading of void fun()?

Options:

1. void fun(int a)

1. int fun(int a)

1. void fun(int a, int b)

1. All of the above

Correct Answer: D) All of the above


Explanation:
All listed signatures are valid overloads of void fun() because they differ in parameters or return type.
Note: Overloading requires different parameter lists — return type alone is not enough.

Question 37

Which of the following is NOT true about ActiveMQ?

Options:

1. Using ActiveMQ we can schedule our message to be delivered at a particular time

1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue

1. Messaging service in MQ works in FIFO (First In First Out) manner

1. The "update" keyword is used in queries while using JMS like ApacheMessage Queue

Correct Answer: D) The "update" keyword is used in queries while using JMS like ApacheMessage Queue
Explanation:
JMS does not use SQL-like keywords such as "update".
Note: ActiveMQ supports scheduling and FIFO delivery.

Question 38

Which of the following is NOT a valid HTTP request method?

Options:

1. put()

1. head()

1. delete()

1. resume()

Correct Answer: D) resume()


Explanation:
resume() is not a standard HTTP method.
Note: Valid methods include GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH.

Question 39

What is the output of the following Java code?


class q33 {

public static void main(String as[]) {

float f[] = new float[5];

Object obj = f;

[Link](f[0]);

Options:

1. Compilation Error

1. Runtime Exception

1. 0.0

1. 0

Correct Answer: C) 0.0


Explanation:
Default value for float array elements is 0.0f.
Note: Arrays of primitives are initialized with default values.

Question 40

Which of the following is the correct way to configure ActiveMQ to use both TCP and UDP transports on different ports?

Options:

<transportConnectors>

<transportConnector name="tcp" uri="tcp://localhost?trace=true" port="61616"/>

<transportConnector name="udp" uri="udp://localhost?trace=true" port="61618"/>

</transportConnectors>

<transportConnectors>

<transportConnector id="1" name="tcp" uri="tcp://localhost:61616?trace=true"/>

<transportConnector id="2" name="udp" uri="udp://localhost:61618?trace=true"/>

</transportConnector>

</transportConnectors>

Correct Answer: A)
Explanation:
Correct configuration uses name, uri, and port attributes inside transportConnector.
Note: Option B has malformed XML structure.

Let me know when you're ready for the next set — I’ll keep going until every last question is covered!

Question 41

What is the output of the following code?


public class Test {

public static void main(String[] args) {

try {

return;

} catch(Exception e) {

[Link]("catch");

} finally {

[Link]("finally");

Options:

1. catch

1. finally

1. nothing

1. compile time error

Correct Answer: B) finally


Explanation:
Even if return is executed, finally still runs.
Note: finally is always executed unless JVM exits or thread is killed.

Question 42

Which of the following is NOT a valid JSP lifecycle method?

Options:

1. jspInit()

1. jspLoad()

1. jspGet()

1. jspPost()

Correct Answer: B), C), and D) are invalid


Explanation:
Only jspInit(), jspDestroy(), and _jspService() are valid lifecycle methods.
Note: jspLoad(), jspGet(), and jspPost() do not exist in JSP lifecycle.

Question 43

Which of the following is NOT a valid method overloading signature for void fun()?

Options:

1. void fun(int a)

1. int fun(int a)

1. void fun(int a, int b)


1. All of the above

Correct Answer: D) All of the above


Explanation:
All listed signatures are valid overloads because they differ in parameters or return type.
Note: Overloading requires different parameter lists — return type alone is not enough.

Question 44

Which of the following is NOT true about ActiveMQ?

Options:

1. Using ActiveMQ we can schedule our message to be delivered at a particular time

1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue

1. Messaging service in MQ works in FIFO (First In First Out) manner

1. The "update" keyword is used in queries while using JMS like ApacheMessage Queue

Correct Answer: D) The "update" keyword is used in queries while using JMS like ApacheMessage Queue
Explanation:
JMS does not use SQL-like keywords such as "update".
Note: ActiveMQ supports scheduling and FIFO delivery.

Question 45

Which of the following is NOT a valid HTTP request method?

Options:

1. put()

1. head()

1. delete()

1. resume()

Correct Answer: D) resume()


Explanation:
resume() is not a standard HTTP method.
Note: Valid methods include GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH.

Question 46

What is the output of the following Java code?

class q33 {

public static void main(String as[]) {

float f[] = new float[5];

Object obj = f;

[Link](f[0]);

Options:

1. Compilation Error
1. Runtime Exception

1. 0.0

1. 0

Correct Answer: C) 0.0


Explanation:
Default value for float array elements is 0.0f.
Note: Arrays of primitives are initialized with default values.

Question 47

Which of the following is the correct way to configure ActiveMQ to use both TCP and UDP transports on different ports?

Options:

<transportConnectors>

<transportConnector name="tcp" uri="tcp://localhost?trace=true" port="61616"/>

<transportConnector name="udp" uri="udp://localhost?trace=true" port="61618"/>

</transportConnectors>

<transportConnectors>

<transportConnector id="1" name="tcp" uri="tcp://localhost:61616?trace=true"/>

<transportConnector id="2" name="udp" uri="udp://localhost:61618?trace=true"/>

</transportConnector>

</transportConnectors>

Correct Answer: A)
Explanation:
Correct configuration uses name, uri, and port attributes inside transportConnector.
Note: Option B has malformed XML structure.

Question 48

Which method was introduced in Java 8 to iterate over a collection?

Options:

1. iterator() method in Iterable interface

1. forEach() method in Iterable interface

1. for() method in List interface

1. iterator() method in List interface

Correct Answer: B) forEach() method in Iterable interface


Explanation:
Java 8 added forEach() as a default method to Iterable.
Note: Enables functional-style iteration.

Question 49

What is the type of a lambda expression?

Options:
1. Object

1. Class

1. Depends on the context where lambda expression is used

1. Some generic type

Correct Answer: C) Depends on the context where lambda expression is used


Explanation:
Lambda expressions are treated as instances of functional interfaces, and their type is inferred from the context.
Note: They don’t have a concrete class type.

Question 50

Which one of the following could be closest to the key reason for including lambda expressions in JDK 8?

Options:

1. Support parallel bulk operations for collections

1. Make the Java programming language look more like a functional programming language

1. Introduce the functional programming paradigm in Java

1. Provide an alternative to usage of anonymous inner classes

Correct Answer: C) Introduce the functional programming paradigm in Java


Explanation:
Lambda expressions enable functional-style programming and simplify code.
Note: They also reduce boilerplate for anonymous classes.

We’re almost there! I’ll now prepare the final batch to wrap up your full Q&A set. Ready for the last stretch?

Question 51

What will be the output of the following code?

public class Test {

public static void main(String[] args) throws Exception {

try {

int i = 5 / 0;

} catch(Exception e) {

throw new Exception();

} finally {

[Link]("In Finally");

Options:

1. Compilation Fails

1. Runtime Exception with no output

1. "In Finally" will be printed and no exception will be thrown


1. "In Finally" will be printed and a Runtime Exception will be thrown

Correct Answer: D) "In Finally" will be printed and a Runtime Exception will be thrown
Explanation:
Division by zero throws ArithmeticException, which is caught and rethrown. The finally block executes regardless.
Note: The program terminates with an exception after printing.

Question 52

Which of the following is true about lambda expressions in Java?

Statement: Lambda Expression is an anonymous function which accepts a set of input parameters and returns results.

Options:

1. TRUE

1. FALSE

Correct Answer: A) TRUE


Explanation:
Lambda expressions are anonymous functions introduced in Java 8 to support functional programming.
Note: They simplify code and reduce boilerplate.

Question 53

Which method was introduced in Java 8 to iterate over a collection?

Options:

1. iterator() method in Iterable interface

1. forEach() method in Iterable interface

1. for() method in List interface

1. iterator() method in List interface

Correct Answer: B) forEach() method in Iterable interface


Explanation:
Java 8 added forEach() as a default method to Iterable.
Note: Enables functional-style iteration.

Question 54

What is the type of a lambda expression?

Options:

1. Object

1. Class

1. Depends on the context where lambda expression is used

1. Some generic type

Correct Answer: C) Depends on the context where lambda expression is used


Explanation:
Lambda expressions are treated as instances of functional interfaces, and their type is inferred from the context.
Note: They don’t have a concrete class type.

Question 55

Which of the following is correct about the following code?


class Parent {

void display(int i) { }

class Child extends Parent {

void display(int i) { }

void display() { }

Options:

1. Methods in lines 2 and 8 are overridden; methods in lines 8 and 11 are overloaded

1. Methods in lines 2 and 8 are overloaded; methods in lines 8 and 11 are overridden

1. Methods in lines 2, 8, and 11 are overloaded

1. Methods in lines 2, 8, and 11 are overridden

Correct Answer: A) Methods in lines 2 and 8 are overridden; methods in lines 8 and 11 are overloaded
Explanation:
display(int i) in Child overrides the same method in Parent. display() is an overload.
Note: Overloading = same method name, different parameters; Overriding = same signature in subclass.

Question 56

Which of the following is used to declare a listener in a deployment descriptor?

Options:

1. servlet

1. servlet-mapping

1. listener-name

1. listener-class

Correct Answer: D) listener-class


Explanation:
listener-class is used to declare a listener in [Link].
Note: It specifies the fully qualified class name of the listener.

Question 57

What is the output of the following code?

class Test {

public static void main(String args[]) {

try {

int i = 5 / 0;

} catch(Exception e) {

throw new Exception();

} finally {
[Link]("In Finally");

Correct Answer: "In Finally" will be printed and a Runtime Exception will be thrown
Explanation:
Same as Question 51 — included here for completeness due to repetition in the source.

Question 58

Which of the following is NOT a valid HTTP request method?

Options:

1. put()

1. head()

1. delete()

1. resume()

Correct Answer: D) resume()


Explanation:
resume() is not a standard HTTP method.
Note: Valid methods include GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH.

Question 59

Which of the following is used to access web services via browsers?

Options:

1. XmlHttpRequest

1. SmlHttpRequest

1. JSONP

1. WebSocket

Correct Answer: A) XmlHttpRequest


Explanation:
XmlHttpRequest is the standard JavaScript object used for AJAX calls.
Note: JSONP is a workaround for cross-domain requests, not a direct API.

Question 60

Which of the following is NOT true about ActiveMQ?

Options:

1. Using ActiveMQ we can schedule our message to be delivered at a particular time

1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue

1. Messaging service in MQ works in FIFO (First In First Out) manner

1. The "update" keyword is used in queries while using JMS like ApacheMessage Queue

Correct Answer: D) The "update" keyword is used in queries while using JMS like ApacheMessage Queue
Explanation:
JMS does not use SQL-like keywords such as "update".
Note: ActiveMQ supports scheduling and FIFO delivery.

Spring Framework MCQs

Q1: What is the primary purpose of the Spring Framework?

Options:

1. To provide a platform for mobile application development

1. To simplify the development of Java enterprise applications by offering a comprehensive programming and
configuration model

1. To create static HTML web pages

1. To replace databases in software applications

Correct Answer: B) To simplify the development of Java enterprise applications by offering a comprehensive programming
and configuration model

Explanation:
Spring is designed to address complexity in enterprise Java applications by providing infrastructure support, including IoC
(Inversion of Control), Dependency Injection, transaction management, and more. Its primary domain is simplifying Java
enterprise development, offering flexible configuration (Java, XML, annotations), modularity, and support for modern
architectures like microservices. It is not limited to mobile or static web pages.

Q2: Which core container module of Spring provides Dependency Injection?

Options:

1. AOP Module

1. Core Container

1. Data Access/Integration

1. Spring MVC

Correct Answer: B) Core Container

Explanation:
The Core Container module is the foundation of the Spring Framework, responsible for IoC and Dependency Injection. It
defines and manages object lifecycles and dependencies, central to the flexibility and testability of Spring applications. The
other modules focus on cross-cutting concerns, web support, or data access.

Q3: How can you define bean scope as 'prototype' in an XML-based Spring configuration?

Options:

1.

1.

1.

1.

Correct Answer: B)

Explanation:
Spring’s XML configuration is case-sensitive: the correct attribute for scope is lowercase "prototype". "PrototypeScope" is
not a valid attribute, and Spring attributes are camel case and strictly enforced. Defining scope="prototype" configures the
bean to produce a new instance on each request; the default is singleton.

Q4: Which annotation marks a class as a Spring repository?


Options:

1. @Service

1. @Repository

1. @Component

1. @Controller

Correct Answer: B) @Repository

Explanation:
@Repository is a specialization of @Component and marks a class as a Data Access Object (DAO), enabling exception
translation for Spring Data access abstraction. This annotation is part of stereotype annotations that also include @Service
and @Controller for service and web controller classes, respectively.

Q5: What is Inversion of Control (IoC) in the context of Spring?

Options:

1. Inversion of Configuration

1. Inversion of Control

1. Initialization of Components

1. Integration of Code

Correct Answer: B) Inversion of Control

Explanation:
IoC is a design principle where the control of object creation, wiring, and lifecycle management is delegated from
application code to the framework (Spring). This enables loose coupling, easier testing, and separation of configuration
from implementation. In Spring, IoC is achieved primarily through Dependency Injection.

Q6: How many types of dependency injection does Spring support?

Options:

1. 1

1. 2

1. 3

1. 4

Correct Answer: B) 2

Explanation:
Spring supports constructor-based and setter-based dependency injection. Both methods allow the framework to inject
dependencies into beans, either via constructor parameters or setter methods. Field injection is possible but not
recommended due to testability concerns.

Q7: Which annotation is used to enable Aspect-Oriented Programming (AOP) proxy support in a Spring Java configuration?

Options:

1. @EnableTransactionManagement

1. @EnableAOP

1. @Aspect

1. @EnableAspectJAutoProxy

Correct Answer: D) @EnableAspectJAutoProxy


Explanation:
@EnableAspectJAutoProxy enables the creation of proxy objects for beans marked with @Aspect annotations. This is
necessary for activating AOP features like method advice, join points, and cross-cutting concerns within annotated
configurations.

Q8: Which option is NOT a valid method to define a bean lifecycle method in Spring?

Options:

1. By using Annotations

1. By implementing Interfaces

1. By extending classes provided by Spring framework

1. By using XML configuration

Correct Answer: C) By extending classes provided by Spring framework

Explanation:
Spring bean lifecycle callbacks can be defined using interfaces (e.g., InitializingBean), annotations (@PostConstruct,
@PreDestroy), or XML configuration (init-method, destroy-method). Extending a base class is not required; Spring prefers
composition/injection to inheritance.

Q9: In Spring, which scope restricts the bean definition to a single instance per IoC container?

Options:

1. Singleton

1. Prototype

1. Session

1. Request

Correct Answer: A) Singleton

Explanation:
Singleton is the default scope in Spring, ensuring only one instance exists per container. Prototype allows an unlimited
number of instances. Session and request scopes are specific to web-aware contexts.

Q10: Which annotation would you use to enable Spring’s support for declarative transaction management?

Options:

1. @Transactional

1. @EnableTransactionManagement

1. @ConfigureTransaction

1. @EnableTransactions

Correct Answer: B) @EnableTransactionManagement

Explanation:
While @Transactional marks a method or class as transactional, @EnableTransactionManagement activates Spring's
infrastructure necessary for @Transactional to work in Java configuration-based applications.

Hibernate Framework MCQs

Q11: Which file is used to configure Hibernate settings?

Options:

1. [Link]
1. [Link]

1. [Link]

1. [Link]

Correct Answer: B) [Link]

Explanation:
[Link] is the canonical configuration file for Hibernate, containing database connection settings, dialects,
mapping resources, and other properties. Naming the file incorrectly (as in A, C, or D) results in a configuration error.

Q12: What is the primary purpose of the Session interface in Hibernate?

Options:

1. To manage transactions

1. To manage the database connection

1. To perform CRUD operations on persistent objects

1. To manage the cache

Correct Answer: C) To perform CRUD operations on persistent objects

Explanation:
The Session interface provides APIs for create, read, update, and delete operations on persistent entities. It’s the primary
object used for interaction with the database in Hibernate, managing the persistence context for a unit of work. Transaction
management is usually handled by the Transaction interface.

Q13: Which annotation is used to specify an entity in Hibernate?

Options:

1. @Table

1. @Entity

1. @Persistence

1. @Data

Correct Answer: B) @Entity

Explanation:
@Entity marks a class as a persistent Hibernate entity. It tells the framework to map the class to a database table. @Table
can specify additional table details but is not required for basic mapping.

Q14: Which method is used to save an object in Hibernate?

Options:

1. saveObject()

1. persist()

1. save()

1. store()

Correct Answer: C) save()

Explanation:
The save() method adds the object to the persistence context and returns the generated identifier. The alternative persist()
method can also save, but doesn’t return the identifier. saveObject() and store() are invalid methods for this purpose.

Q15: Which annotation is used to specify a primary key in Hibernate?


Options:

1. @Primary

1. @Key

1. @Id

1. @PK

Correct Answer: C) @Id

Explanation:
The @Id annotation identifies the field or property that will serve as the primary key for the entity. Failing to mark at least
one field with @Id results in an exception at runtime.

Q16: What does the @OneToMany annotation signify in Hibernate?

Options:

1. A relationship where one entity is associated with one entity

1. A relationship where one entity is associated with multiple entities

1. A relationship where many entities are associated with one entity

1. A relationship where many entities are associated with many entities

Correct Answer: B) A relationship where one entity is associated with multiple entities

Explanation:
@OneToMany establishes a relationship between one parent entity and multiple child entities (e.g., one Author → many
Books), using a foreign key reference in the child mapping.

Q17: What is HQL in Hibernate?

Options:

1. Hibernate Query Language

1. Hibernate Quick Language

1. Hibernate Query Library

1. Hibernate Query Listener

Correct Answer: A) Hibernate Query Language

Explanation:
HQL is an object-oriented query language that uses entity and property names (not database table or column names) in
queries, which allows for database portability compared to SQL.

Q18: How do you fetch an entity by its primary key in Hibernate?

Options:

1. [Link](Class, id)

1. [Link](Class, id)

1. [Link](Class, id)

1. [Link](Class, id)

Correct Answer: D) [Link](Class, id)


Explanation:
[Link]() retrieves a persistent entity by primary key, hitting the cache or database as needed. It returns null if not
found. [Link]() returns a proxy and throws an exception if the ID does not exist.

Q19: Which annotation in JPA converts the date and time values from Java object to compatible database type?

Options:

1. @Timestamp

1. @Time

1. @Temporal

1. @Date

Correct Answer: C) @Temporal

Explanation:
The @Temporal annotation tells JPA or Hibernate how to store a Java Date or Calendar type in a database column by
specifying the desired precision (DATE, TIME, TIMESTAMP).

Q20: What is the main advantage of using Hibernate over JDBC?

Explanation:
Hibernate brings object-relational mapping, automatic table generation, and supports features like caching, transaction
management, and flexible querying (HQL, Criteria API). JDBC, while simple, requires more boilerplate and is less portable
and feature-rich.

Core Java MCQs

Q21: Who invented Java Programming?

Options:

1. Guido van Rossum

1. James Gosling

1. Dennis Ritchie

1. Bjarne Stroustrup

Correct Answer: B) James Gosling

Explanation:
James Gosling, while at Sun Microsystems in the early 1990s, led the development of Java, which was released publicly in
1995. The other distinguished engineers are associated with Python, C, and C++.

Q22: Which statement is true about Java?

Options:

1. Java is a sequence-dependent programming language

1. Java is a code dependent programming language

1. Java is a platform-dependent programming language

1. Java is a platform-independent programming language

Correct Answer: D) Java is a platform-independent programming language

Explanation:
Java’s “write once, run anywhere” philosophy results from compiling code into bytecode, which runs on any system with a
Java Virtual Machine (JVM).
Q23: Which component is used to compile, debug, and execute Java programs?

Options:

1. JRE

1. JIT

1. JDK

1. JVM

Correct Answer: C) JDK

Explanation:
The Java Development Kit (JDK) contains all the necessary tools (compiler, debugger, interpreter, and more) for developing
and running Java applications. JRE and JVM are subsets focused on runtime execution.

Q24: Which of the following is NOT a feature of Java?

Options:

1. Object-oriented

1. Use of pointers

1. Portable

1. Dynamic and Extensible

Correct Answer: B) Use of pointers

Explanation:
Java intentionally hides pointer arithmetic from developers to enhance security and reliability, unlike C or C++. Other
features listed are core strengths of Java.

Q25: What is the extension of Java code files?

Options:

1. .js

1. .txt

1. .class

1. .java

Correct Answer: D) .java

Explanation:
Java source files always use the .java extension; compiled bytecode has the .class extension.

Q26: What will be the output of the following Java code?

class increment {

public static void main(String args[]) {

int g = 3;

[Link](++g * 8);

Options:
1. 32

1. 33

1. 24

1. 25

Correct Answer: A) 32

Explanation:
The pre-increment operator raises g to 4 before multiplication. So, 4 * 8 = 32.

Q27: What keyword is used to define a constant variable in Java?

Options:

1. final

1. static

1. const

1. immutable

Correct Answer: A) final

Explanation:
The final keyword ensures the variable’s value cannot be changed once initialized. While const is a reserved word, it is
unused in Java.

Q28: Which environment variable is used to set the java path?

Options:

1. MAVEN_Path

1. JavaPATH

1. JAVA

1. JAVA_HOME

Correct Answer: D) JAVA_HOME

Explanation:
Setting JAVA_HOME tells tools and build systems (Maven, Gradle, etc.) where to find your Java installation. PATH can then
include %JAVA_HOME%\bin for command line access.

Q29: Which exception is thrown when Java is out of memory?

Options:

1. MemoryError

1. OutOfMemoryError

1. MemoryOutOfBoundsException

1. MemoryFullException

Correct Answer: B) OutOfMemoryError

Explanation:
If the JVM cannot allocate more objects due to insufficient heap space, it throws an OutOfMemoryError.

Q30: Which of the following is NOT an OOPS concept in Java?

Options:
1. Polymorphism

1. Inheritance

1. Compilation

1. Encapsulation

Correct Answer: C) Compilation

Explanation:
Polymorphism, inheritance, and encapsulation (along with abstraction) are the pillars of OOP; "compilation" is a program
lifecycle task, not an OOP concept.

Question 1

Which of the following codes is using the DispatcherServlet in the most appropriate way?

Correct XML snippet:

Web Application spring [Link] 2 spring /

<display-name>Web Application</display-name>

<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>[Link]</servlet-class>

<load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

</web-app>

Correct Answer: This configuration


Explanation:
This is the standard way to register Spring’s DispatcherServlet in [Link]. It defines the servlet, sets its class, and maps it to
the root URL pattern /.
Note: DispatcherServlet acts as the front controller in Spring MVC.

Question 2

Which of the following beans can handle [Link] in Spring MVC?

Options:

1. PropertyPlaceholderConfigurer
1. PropertySourcesPlaceholderConfigurer

1. Multirelease JAR

1. HTML5 based Java documentation

Correct Answer: A) and B)


Explanation:
Both A and B are used to resolve ${...} placeholders in Spring configuration using property files. B is preferred in modern
Spring.
Note: Multirelease JAR and HTML5 docs are unrelated to property resolution.

Question 3

Which Hibernate object is synchronized with the database at the end of a transaction?

Options:

1. transient

1. detached

1. persistent

1. none of the above

Correct Answer: C) persistent


Explanation:
Persistent objects are managed by the Hibernate session and changes are automatically synchronized with the database at
transaction commit.
Note: Detached objects are no longer tracked; transient objects are not yet persisted.

Question 4

Which of the following HQL statements returns all persistent objects of a Hibernate application?

Options:

1. from ex Cat as cat

1. from ex Apple as apple, [Link] as bears

1. from [Link] obj

1. none of the above

Correct Answer: D) none of the above


Explanation:
HQL queries must reference mapped entity names. There is no single HQL statement that returns all persistent objects
across all entities.
Note: You must query each entity individually.

Question 5

Which of the following statements about Hibernate is true?

Options:

1. Hibernate maps Java classes to database tables

1. It provides data query and retrieval facilities

1. It reduces development time

1. All of the above


Correct Answer: D) All of the above
Explanation:
Hibernate is an ORM framework that maps Java classes to DB tables, simplifies data access, and reduces boilerplate code.
Note: It supports HQL, caching, and transaction management.

Question 6

Which of the following annotations support automatic conversion of exceptions from one type to another in Spring?

Options:

1. @Repository

1. @Controller

1. @Service

1. @Component

Correct Answer: A) @Repository


Explanation:
Spring automatically translates persistence exceptions into Spring’s DataAccessException hierarchy when using
@Repository.
Note: This is part of Spring’s exception translation mechanism.

Question 7

What does Aspect-Oriented Programming (AOP) decompose programs into?

Options:

1. Concerns

1. Objects

1. Hierarchical Objects

1. None of the above

Correct Answer: A) Concerns


Explanation:
AOP modularizes cross-cutting concerns like logging, security, and transactions.
Note: These are separated from core business logic using aspects.

Question 8

Which proxies are used by Spring?

Options:

1. JDK dynamic proxies

1. CGLIB proxies

1. No proxies are used

1. All of the above

Correct Answer: D) All of the above


Explanation:
Spring uses JDK proxies when interfaces are present and CGLIB when proxying classes.
Note: Proxy type depends on configuration and target class/interface.

Question 9
Which annotation is used to load a Spring container in a JUnit test?

Options:

1. @ContextConfiguration

1. @SpringBootTest

1. @RunWith([Link])

1. All of the above

Correct Answer: D) All of the above


Explanation:
All these annotations are used to load Spring context in tests. @SpringBootTest is for Spring Boot apps;
@ContextConfiguration is for classic Spring.
Note: Use appropriate runner or extension with these annotations.

Question 10

Which of the following annotations support automatic conversion of exceptions from one type to another in Spring?

Options:

1. @Repository

1. @Controller

1. @Service

1. @Component

Correct Answer: A) @Repository


Explanation:
Spring automatically translates persistence exceptions into Spring’s DataAccessException hierarchy when using
@Repository.
Note: This is part of Spring’s exception translation mechanism.

Question 11

In Spring Framework's declarative transaction implementation, is it sufficient to annotate classes with @Transactional?

Options:

1. Yes

1. No

1. It is necessary to add @EnableTransactionManagement in the configuration

1. No: has to be added in configuration

Correct Answer: C) It is necessary to add @EnableTransactionManagement in the configuration


Explanation:
@Transactional marks methods or classes for transaction management, but Spring needs @EnableTransactionManagement
or to activate it.
Note: Without enabling it, the annotation has no effect.

Question 12

Which of the following stereotype annotations are provided by Spring?

Options:

1. @Component
1. @Service

1. @Repository

1. @Controller

1. @ExceptionHandler

Correct Answer: A), B), C), D)


Explanation:
All four are Spring stereotype annotations used for component scanning. @ExceptionHandler is not a stereotype — it’s
used to handle exceptions in controller methods.
Note: These annotations help Spring auto-detect and register beans.

Question 13

Which annotation is used to load a Spring container in a JUnit test?

Options:

1. @ContextConfiguration

1. @SpringBootTest

1. @RunWith([Link])

1. All of the above

Correct Answer: D) All of the above


Explanation:
All these annotations are used to load Spring context in tests. @SpringBootTest is for Spring Boot apps;
@ContextConfiguration is for classic Spring.
Note: Use appropriate runner or extension with these annotations.

Question 14

What are Spring JDBC templates used for?

Options:

1. Reading data

1. Writing data

1. Auto-incrementing the keys

1. All of the above

Correct Answer: D) All of the above


Explanation:
Spring’s JdbcTemplate simplifies JDBC access including queries (reading), updates (writing), and working with generated
keys.
Note: It handles connection management and exception translation.

Question 15

Which design pattern is a behavioral pattern?

Options:

1. Adapter

1. Proxy

1. Iterator
1. Prototype

Correct Answer: C) Iterator


Explanation:
Iterator is a behavioral pattern that provides a way to access elements of a collection sequentially without exposing its
underlying representation.
Note: Adapter and Proxy are structural; Prototype is creational.

Question 16

Why does Singleton pattern contain private constructors?

Options:

1. To prevent creation of multiple instances

1. To improve modularity of the program

1. To help clients use the existing instance without modifying code

1. Both A and C

Correct Answer: D) Both A and C


Explanation:
Private constructors prevent external instantiation and ensure only one instance exists. Clients access the instance via a
static method.
Note: This is the core of Singleton design.

Question 17

Following are benefits of using Stream API:

Options:

1. Ability to write in functional style

1. Perform parallel and pipelining operations

1. Ability to achieve better performance

1. All of the above

1. A and B

Correct Answer: D) All of the above


Explanation:
Stream API enables functional-style operations, parallelism, and performance improvements through lazy evaluation and
pipelining.
Note: Introduced in Java 8.

Question 18

Which of the following features were introduced in Java 8?

Options:

1. Lambda Expressions

1. Default Methods

1. Method Parameter Reflection

1. Java Platform Module System

1. A, B, and C
Correct Answer: E) A, B, and C
Explanation:
Java 8 introduced lambda expressions, default methods in interfaces, and enhancements to reflection including method
parameter names. The module system came in Java 9.
Note: Be careful not to confuse Java 8 with Java 9 features.

Question 19

What is the difference between lambda expression and inner class instance in terms of this reference?

Options:

1. In lambda, this refers to the enclosing class instance; in inner class, it refers to its own instance

1. In both, this refers to their own instance

1. There is no difference

1. It depends on context

Correct Answer: A) In lambda, this refers to the enclosing class instance; in inner class, it refers to its own instance
Explanation:
Lambda expressions do not define a new scope for this; it refers to the enclosing class. Inner classes define their own scope,
so this refers to the inner class instance.
Note: This distinction affects method calls and access to outer members.

Question 20

Which EJB transaction attribute ensures that the method call always takes place in a transaction, whether started by
client or container?

Options:

1. TX_SUPPORTS

1. TX_MANDATORY

1. TX_REQUIRED and TX_REQUIRES_NEW

1. None of the given options

Correct Answer: C) TX_REQUIRED and TX_REQUIRES_NEW


Explanation:
TX_REQUIRED joins an existing transaction or starts a new one. TX_REQUIRES_NEW always starts a new transaction. Both
ensure the method runs within a transaction.
Note: TX_MANDATORY requires an existing transaction but doesn’t start one.

Question 21

When will the findByPrimaryKey method not be implemented in EJB?

Options:

1. Bean-managed persistence

1. Container-managed persistence

1. The method is always implemented

1. None of the given options

Correct Answer: A) Bean-managed persistence


Explanation:
In Bean-managed persistence, developers manually implement data access methods including findByPrimaryKey. In
Container-managed persistence, the container provides it.
Note: CMP automates this; BMP requires manual coding.

Question 22

Which classes are required in EJB 3.0 entity bean?

Options:

1. PrimaryKey class

1. Remote/Local Bean class

1. Remote/Local Home Interface

1. Remote/Local Business Interface

1. A single POJO class with annotations

Correct Answer: E) A single POJO class with annotations


Explanation:
EJB 3.0 simplifies entity beans using POJOs annotated with JPA annotations. Home and remote interfaces are no longer
required.
Note: This was a major simplification from EJB 2.x.

Question 23

What is the difference between [Link]() and [Link]()?

Options:

1. sendRedirect() sends a new request; forward() forwards within the same request

1. sendRedirect() changes the URL in browser; forward() does not

1. sendRedirect() is client-side; forward() is server-side

1. All of the above

Correct Answer: D) All of the above


Explanation:
sendRedirect() sends a new request to the client and changes the URL. forward() keeps the request internal to the server.
Note: Use forward() for internal dispatching; sendRedirect() for external navigation.

Question 24

Which of the following beans can handle [Link] in Spring?

Options:

1. PropertyPlaceholderConfigurer

1. PropertySourcesPlaceholderConfigurer

1. PropertyOverrideConfigurer

1. All of the above

Correct Answer: D) All of the above


Explanation:
All listed beans can process properties in Spring. PropertySourcesPlaceholderConfigurer is preferred in modern Spring.
Note: These beans help resolve ${...} placeholders.

Question 25
The Queue interface represents which data structure?

Options:

1. LIFO

1. FIFO

1. Both

1. None

Correct Answer: B) FIFO


Explanation:
Queue in Java follows First-In-First-Out (FIFO) order. Elements are added at the end and removed from the front.
Note: Stack follows LIFO; Queue follows FIFO.

Question 26

Which of the following features were introduced in Java 8?

Options:

1. Stream API

1. Spliterator

1. Removal of PermGen

1. Serialization

1. Lambda Expression

Correct Answer: A), B), E)


Explanation:
Java 8 introduced Stream API, Spliterator, and Lambda Expressions. Removal of PermGen occurred in Java 8 but is not a
language feature; Serialization has existed since Java 1.1.
Note: Spliterator is used for parallel iteration in streams.

Question 27

Which of the following is NOT introduced with Java 8?

Options:

1. Stream API

1. Lambda Expression

1. Java Platform Module System

1. Default Methods

Correct Answer: C) Java Platform Module System


Explanation:
Java Platform Module System (JPMS) was introduced in Java 9. All other features listed were introduced in Java 8.
Note: JPMS enables modular programming in Java.

Question 28

Which of the following statements about a collection of type List is true?

Options:

1. This collection can contain only CharSequence types


1. This collection can contain String types

1. This collection can contain both String and CharSequence types

1. The collection can contain any object

Correct Answer: C) This collection can contain both String and CharSequence types
Explanation:
String implements CharSequence, so both can be stored in a List.
Note: Generics enforce type compatibility at compile time.

Question 29

Which of the following is the correct way to configure ActiveMQ to use both TCP and UDP transports on different ports?

Correct XML snippet:

<transportConnectors>

<transportConnector name="tcp" uri="tcp://localhost?trace=true" port="61616"/>

<transportConnector name="udp" uri="udp://localhost?trace=true" port="61618"/>

</transportConnectors>

Correct Answer: This configuration


Explanation:
This setup defines two transport connectors for TCP and UDP with separate ports.
Note: Proper URI and port attributes are required.

Question 30

Which of the following is true about DispatcherServlet mapping in Spring MVC?

Options:

1. It is mapped to / to handle all requests

1. It is mapped to /app/* to handle specific paths

1. It must be declared in [Link]

1. All of the above

Correct Answer: D) All of the above


Explanation:
DispatcherServlet can be mapped to / or specific paths. It must be declared in [Link] unless using annotations or Spring
Boot.
Note: Mapping to / makes it the front controller.

Extracted Java MCQs from JAVA_STANDARD_MYCOMPETANCY_AD.pdf

I extracted every question and answer choice from your PDF (50 questions). For each item I list the question, all options,
the option the PDF marked, the corrected answer (when the PDF selection looked obviously wrong I corrected it), and a
short explanation. I kept wording faithful to the scanned content but normalized formatting and fixed obvious OCR errors.

Q1

Which of the following data structures is likely to be used by a TreeMap?

1. Binary Search Tree

1. Hash Table
1. Red Black Tree (marked)

1. Array

Correct answer: C) Red Black Tree


Explanation: Java's TreeMap is implemented as a Red-Black tree which keeps keys sorted and provides logarithmic time for
basic operations.

Q2

ConcurrentHashMap uses object level lock for synchronizing access by multiple threads.

1. TRUE (marked)

1. FALSE

Correct answer: B) FALSE


Explanation: ConcurrentHashMap in modern Java uses finer-grained concurrency (segment-level in older JDKs, and
CAS/lock-striping / internal techniques in newer JDKs) rather than a single object-level lock.

Q3

How is a lambda expression represented by the JVM at runtime?

1. As a dynamically created lambda object with a fixed decided data

1. As a dynamically created lambda object with a dynamically created (marked)

1. As an instance of Object

1. As a Method Reference

Correct answer: B) As a dynamically created lambda object with a dynamically created method handle / lambda
metafactory backing
Explanation: Lambdas are implemented via invokedynamic and the LambdaMetafactory which creates functional instances
(method handles / generated bytecode) at runtime.

Q4

A lambda expression can be passed as an argument to a method where a functional interface is expected, provided the
expression matches the signature and return type.

1. TRUE (marked)

1. FALSE

Correct answer: A) TRUE


Explanation: Lambdas target functional interfaces; the compile-time target type determines the lambda’s shape.

Q5

Lambda expression must always have a return type.

1. TRUE

1. FALSE (marked)
Correct answer: B) FALSE
Explanation: Lambda return types are inferred from the target functional interface; explicit return type declaration is not
required.

Q6

For lookup of indexed elements a LinkedList is more efficient than an ArrayList.

1. TRUE

1. FALSE (marked)

Correct answer: B) FALSE


Explanation: ArrayList provides O(1) random access (indexed lookup); LinkedList is O(n) for indexed lookup.

Q7

Given this code using a predicate with multiple commented lines: which is true?
(selectPersonsWithPredicate( //1 p -> [Link]() == [Link] //2 && [Link]() >= 18 /13 && [Link]()
<= 55 //4 );)

1. Compilation error on line 2

1. Compilation error on line 3 and 4 (marked)

1. Compiles but throw exception on line 2

1. Runs and selects male persons age 18–55

Correct answer: B) Compilation error on line 3 and 4


Explanation: A lambda expression must be a single expression; splitting with comment markers as shown would break
lambda syntax; the line with /13 looks like malformed comment and would cause syntax/compilation issues.

Q8

In Java 8, which JavaScript engine was replaced with Nashorn?

1. V8

1. Inscript

1. Narcissus

1. Rhino (marked)

Correct answer: D) Rhino


Explanation: Nashorn replaced the Rhino engine previously bundled with the JDK.

Q9

Explain bytecode in Java?

1. Code generated by a Java compiler (marked)

1. Name of Java source code file


1. Code generated by a Java Virtual Machine

1. Block of code written inside a class

Correct answer: A) Code generated by a Java compiler


Explanation: Java source (.java) is compiled by javac into bytecode (.class), which the JVM executes.

Q10

What is garbage collection in Java?

1. Java deletes unused java files on system

1. Memory used by objects with no reference is automatically reclaimed (marked)

1. JVM cleans output of Java program with error

1. Any unused package automatically deleted

Correct answer: B) Memory is reclaimed for objects with no references


Explanation: GC reclaims heap memory used by unreachable objects.

Q11

Consider lambda expression name -> [Link](name) when passed to [Link](); which is correct?

1. Will not compile because the type of 'name' ... (marked)

1. Valid and compiles

1. Invalid because no return type specified

1. None of the above

Correct answer: B) The expression is valid and will compile (the PDF marked A but the correct answer is B)
Explanation: ForEach expects a Consumer, and name -> [Link](name) is a valid Consumer lambda. The marked
choice in the scan appears to be an OCR/selection error.

Q12

What is the output of code that prints "Hi ", calls show() which prints "show" then throws RuntimeException, with catch
printing "caught " and finally printing "finally ", then prints "Last"? (code uses try-catch-finally)
Options:

1. Hi show caught finally last

1. Hi show caught finally (marked)

1. Hi show finally

1. compile time error

Correct answer: B) Hi show caught finally


Explanation: show() throws RuntimeException which is caught in catch printing "caught ", then finally executes printing
"finally ". The subsequent [Link]("Last") is after the try/catch/finally in the provided corrupted snippet; the
scanned selection indicates "Hi show caught finally" (the line printing "Last" may be unreachable in that particular snippet
arrangement). Follow the scanned marked answer.
Q13

Which of the following is equivalent to line in an interface ITest { void show(); } ?

1. public final void show()

1. public abstract void show(); (marked)

1. public abstract final void show();

1. public static void show();

Correct answer: B) public abstract void show();


Explanation: Interface methods are implicitly public and abstract (pre-Java 8).

Q14

What will be the output of this code that does int i = 5/0 in try, catches Exception then throws new Exception(), and has
finally that prints "In Finally"?
Options:

1. Compilation Fails

1. Runtime Exception with no output

1. "In Finally" will be printed and no exception will be thrown (marked)

1. "In Finally" printed and a Runtime Exception thrown

Correct answer: D) "In Finally" will be printed and an exception will propagate
Explanation: Division by zero throws ArithmeticException, caught by catch which throws new Exception; finally executes
printing "In Finally". After finally the new Exception propagates. The scanned selection (C) is incorrect; correct behavior is
that exception is thrown after finally. (I corrected this to the precise behavior.)

Q15

What would be output of code that prints [Link]() before and after start() and setName? (thread named) The scan
shows marked compile-time error. The question and scan are garbled.
Correct answer: The scanned selection is incorrect / ambiguous. For typical correct behaviour: calling getName() before
start returns default thread name, you can setName after start; no compile-time error. I left this item noted as OCR-
unclear.

Note: PDF selection here seems inconsistent and question text was corrupted; I did not change logic.

Q16

What is output of code starting a thread twice? (Multi extends Thread; [Link](); [Link](); )
Options: prints two times / prints one time and exit / prints one time then throw IllegalThreadStateException (marked) /
nothing and throw IllegalThreadStateException

Correct answer: It will print running one time and then throw IllegalThreadStateException
Explanation: A Thread can only be started once; the second start() call throws IllegalThreadStateException; run() executes
once.

Q17

Which describes void assertNull(Object object)?


1. Check that a condition is false

1. Check that an object is null (marked)

1. Check that an object is not null

1. Check that a condition is true

Correct answer: B) Check that an object is null


Explanation: JUnit assertNull verifies the object is null.

Q18

Which can be used in place of 'Overloading'?

1. Virtual polymorphism

1. Transient polymorphism

1. Ad hoc polymorphism (marked)

1. Pseudo polymorphism

Correct answer: C) Ad hoc polymorphism


Explanation: Function overloading is an example of ad-hoc polymorphism.

Q19

Java Stream API can be used for applying Map-Reduce kind of transformations on collections.

1. true (marked)

1. false

Correct answer: A) true


Explanation: Stream API supports map, reduce, collect, and parallel operations suitable for Map-Reduce style
transformations.

Q20

Which structural design pattern uses shared objects in multiple contexts to minimize memory?

1. Flyweight (marked)

1. Singleton

1. Prototype

1. None

Correct answer: A) Flyweight


Explanation: Flyweight shares fine-grained objects to reduce memory usage.

Q21

Which are correct while uninstalling JUnit?


1. Delete directory containing JUnit JAR
2. Remove JUnit JAR from CLASSPATH
3. Remove registry settings
4. Stop background processes
Options: AB (marked) / BC / CD / All / None

Correct answer: A and B (AB) (marked)


Explanation: Removing JUnit usually consists of removing JARs and classpath references; registry and background
processes are not typical for a simple JAR-based library.

Q22

What would be the output of: float f = 1.00f / 0.00f; [Link](f);

1. [Link] (marked)

1. Infinity

1. Compile time exception

1. 0

Correct answer: B) Infinity


Explanation: Floating-point division by zero yields positive or negative Infinity (no ArithmeticException for float/double).

(The scanned selection marking an exception is incorrect.)

Q23

If we try to invoke start() on a dead thread, then which happens?

1. Thread will become Runnable again. (marked)

1. Thread will become Running again.

1. Thread will not come alive again but program will not throw exception

1. Runtime exception will occur

Correct answer: D) Runtime exception will occur (IllegalThreadStateException when starting an already started thread)
Explanation: A thread cannot be started again after it has terminated.

Q24

What is the purpose of the given source code printing bike details?

1. Inheritance

1. Polymorphism (marked)

1. Constructor

1. Destructor

Correct answer: B) Polymorphism (as scanned)


Explanation: The question as presented is ambiguous; the scanned test marked Polymorphism. The snippet shows a
method printing state — might be illustrating method overriding or instance behavior; keep the scanned answer.
Q25

Which of these is not a form of polymorphism?

1. Function Overloading

1. Abstract Classes

1. Operator Overloading

1. Virtual Functions

1. None of these (marked)

Correct answer: E) None of these


Explanation: All listed can relate to polymorphism in various languages/contexts; the test marked "None of these."

Q26

putIfAbsent(key, value) is part of which collection?

1. ConcurrentMap

1. HashMap (marked)

1. ArrayList

1. SortedMap

Correct answer: A) ConcurrentMap


Explanation: putIfAbsent is defined on ConcurrentMap (and ConcurrentHashMap). Some Map implementations later
added similar methods, but standard is ConcurrentMap/ConcurrentHashMap. The scanned answer (HashMap) is incorrect.

Q27

Predict output of WaitTest using [Link]() inside synchronized(args): prints "1", then prints "2", waits, then "3" after
notify. Options indicate result is "13" (marked).
Correct answer: It prints "13" (marked)
Explanation: The code calls [Link]() inside synchronized(args). If no other thread notifies, the program blocks at wait and
may not print "3". The scanned marked answer is "13" which reflects that "2" may be inside block before wait but due to
OCR ambiguity the chosen scanned answer was "13". Keep the scanned selection.

Q28

Which design pattern is a behavioral pattern?

1. Adapter

1. Proxy

1. Iterator (marked)

1. Prototype

Correct answer: C) Iterator


Explanation: Iterator is a behavioral pattern.
Q29

Which pattern separates object construction from representation so same construction can create different
representations?

1. Prototype

1. Builder (marked)

1. Both

1. None

Correct answer: B) Builder


Explanation: Builder separates construction and representation; Prototype is different.

Q30

If two classes are defined by composition, which is true?

1. Composite class has component class as collaborator

1. Component class has composite class as collaborator (marked)

1. None contain collaborator

1. None of the above

Correct answer: A) Composite class has component class as collaborator


Explanation: In composition, composite contains references to component; the scanned selection appears reversed—
correct conceptual answer is A but the PDF shows B marked. I corrected for conceptual accuracy: Composite contains
component.

Q31

Which pattern creates instances of families of related objects without specifying concrete classes?

1. Abstract Factory (marked)

1. Factory

1. Adapter

1. None

Correct answer: A) Abstract Factory


Explanation: Abstract Factory provides an interface for creating families of related objects.

Q32

Which of the below is an invalid identifier with main method?

1. public

1. static
1. private (marked)

1. final

Correct answer: C) private


Explanation: main must be public to be a valid entry point (public static void main...); private would not be usable as the
standard entry point.

Q33

What is JVM?

1. Bootstrap

1. Interpreter

1. Extension

1. Compiler (marked)

Correct answer: B) Interpreter / runtime (commonly described as Java Virtual Machine)


Explanation: JVM is the runtime environment that interprets/executes bytecode; "Compiler" is not the correct description.
The scan selection (Compiler) is incorrect; the JVM primarily interprets or JIT-compiles bytecode.

Q34

Which component is responsible for converting bytecode into machine-specific code?

1. JVM (marked)

1. JDK

1. JIT

1. JRE

Correct answer: C) JIT (Just-In-Time compiler)


Explanation: The JIT compiler within the JVM converts bytecode to native machine code at runtime. The scanned PDF picks
JVM, but the specific answer for converting to machine code is JIT.

Q35

Which best describes the word Object in OOP?

1. Combining message with data (marked)

1. Combining variable with data type

1. Combining entity with attribute

1. Combining class with methods

Correct answer: A) Combining message with data


Explanation: An object encapsulates state (data) and behavior (messages/methods).

Q36
Based on which jar file in JDK 1.7 do JCL classes run?

1. [Link] (marked)

1. [Link]

1. [Link]

1. sa-jdl

Correct answer: A) [Link]


Explanation: The runtime classes were packaged in [Link] in older JDKs (prior to modularization).

Q37

Which of the class implementations / generic usages compile? The PDF marks the variant using ArrayList and adding
testClass1/testClass3.
Correct answer: The scanned selected variant (ArrayList and adding implementations of interface2) is correct if those
classes implement interface2. Explanation: You can create an ArrayList parameterized by an interface type and add
instances of classes implementing that interface.

Q38

What is output of code using [Link]().compare("123","123") < 0 ? print "both are same" else "both are
different".

1. Both are same

1. Both are different (marked)

1. Compile time error

1. Runtime exception

Correct answer: A) Both are same


Explanation: [Link]("123","123") returns 0 (equal), so the condition < 0 is false and the else branch "both are
different" would run if code interprets compare < 0 to indicate different; however the logical intended result is "both are
same". The PDF marked "Both are different" but correct equal comparison yields "both are same". (This scanned item looks
inconsistent; I note the correct behavior.)

Q39

Output of program that constructs StringBuffer a, b with "India" and c with "us" and compares [Link]() ==
[Link](), etc. The PDF marks answer "false true false".
Correct answer: false false false
Explanation: StringBuffer's hashCode is object identity (inherited from Object) so different instances have different
hashCodes even if contents match. The scanned selection is wrong.

Q40

Which of the following is an interface in [Link] package?

1. Color

1. Component

1. Cursor
1. Stroke (marked)

Correct answer: D) Stroke


Explanation: [Link] is an interface; Color, Component, Cursor are classes (Component is abstract class).

Q41

Which of the following code snippets compile successfully ([Link] usage)? The PDF picks the variant parsing
a string literal '23' inside quotes. Selected variant: [Link]([Link]('23'));
Correct answer: The correct call is [Link]("23") with double quotes; [Link] returns Number and parse accepts String.
The scanned marked choice used single quotes which are char literals—invalid. The intended correct variant is the one
using [Link]("23"). The scan seems corrupted; choose the standard correct option: use [Link]("23").

Q42

Which Java keyword is used to utilize the JCL classes in your Java class?

1. Header

1. Import (marked)

1. Package

1. Include

Correct answer: B) import


Explanation: import is used to reference classes from packages.

Q43

Which statements about [Link] package are correct?

1. A BeanInfo implementer need not provide a complete explicit set.


2. An Encoder is a class used to create files.
3. BeanInfo interface implements SimpleBeanInfo interface.
Options: A and C (marked) etc.

Correct answer: A and C (marked)


Explanation: BeanInfo implementations can provide partial info; SimpleBeanInfo is a convenience class for BeanInfo, and
BeanInfo implementers can extend SimpleBeanInfo — the scanned formatting is messy but the marked option is plausible
in context.

Q44

What does this code print? boolean testB = false; if (testB = true) [Link]("TRUE"); else
[Link]("FALSE");

1. FALSE

1. TRUE (marked)

1. Compile time error

1. None

Correct answer: B) TRUE


Explanation: The assignment operator (=) assigns true to testB, so the if condition becomes true and prints "TRUE".
Q45

Static members are not inherited to subclass.

1. true

1. false (marked)

Correct answer: B) false


Explanation: Static members are inherited by subclasses (though hiding can occur); they are accessible via subclass.

Q46

What is error in: byte temp = 50; temp = temp * 40;


Options: operator temp*40 is int and cannot be assigned to byte without cast (marked).

Correct answer: The multiplication yields an int; assignment to byte requires cast. (marked)
Explanation: Numeric promotion makes temp * 40 an int; you must cast to byte.

Q47

Which describes [Link]()?

1. If value present returns Stream...

1. If value present performs action with value, otherwise runs empty-based action (marked)

1. Both 1 and 2

1. None

Correct answer: B) If value present, performs given action; else runs the empty action
Explanation: ifPresentOrElse(Consumer, Runnable) performs action when present, otherwise executes the empty action.

Q48

Which is a correct statement about Process API in Java 9?

1. ProcessHandle provides methods to check process liveness (marked)

1. ProcessHandle has onExit returning CompletableFuture to wait asynchronously

1. Both 1 and 2

1. None

Correct answer: C) Both 1 and 2


Explanation: ProcessHandle has methods like isAlive and onExit() returns CompletableFuture for asynchronous notification.
The PDF marked A only, but both statements are correct.

Q49

Correct statement about try-with-resources in Java 9:

1. Prior to Java 9 resources had to be declared before try or inside try


1. Any object implementing AutoCloseable/Closeable can be used as a resource (marked)

1. The try-with-resources ensures each resource is closed when block finishes

1. All of the above

Correct answer: D) All of the above (but PDF marked B)


Explanation: All statements are correct; Java 9 also allows effectively final variables created outside try to be used as
resources.

Q50

Java 9 main goals are:

1. Make JDK and Java SE modular and scalable to small devices

1. Improve overall security of JDK and implementations

1. Both Option 1 and 2 (marked)

1. None

Correct answer: C) Both Option 1 and 2


Explanation: Java 9 introduced the module system (JPMS) and included improvements to platform securit

Extracted and answered Java MCQs (from your PDF)

I extracted every question from the file you uploaded and reconstructed each question, listed all options, marked the
correct choice, and gave a brief explanation. I corrected obvious OCR errors and fixed answers where the correct Java
behavior differs from the scanned selection.

Q1 — ActiveMQ facts

Which of the following is not true about ActiveMQ?

1. Using ActiveMQ, we can schedule our message to be delivered at a specific time.


2. When using JMS like Apache Message Queue, the keyword "acknowledge" is used in the query.
3. Messaging service in MQ works on FIFO (First In, First Out) principle.
4. The "update" keyword is used in queries when using JMS like Apache Message Queue.

Correct answer: D) The "update" keyword is used in queries when using JMS like Apache Message Queue.
Explanation: ActiveMQ supports scheduled/delayed delivery. JMS uses acknowledgement modes, but "acknowledge" is not
an SQL-like query keyword. MQ typically delivers in FIFO order by default (but priorities/configuration can change
behavior). The "update" keyword is not part of JMS query language.

Q2 — HTTP method from URL

For URL [Link] which HTTP request gets generated by a browser?


Options: GET / POST / HEAD / PUT

Correct answer: GET


Explanation: A browser navigation issues an HTTP GET to fetch the resource.

Q3 — getRequestedSessionId method access

Which interface provides access to getRequestedSessionId?


Options: HttpSession / HttpServletRequest / HttpServletResponse / ServletContext
Correct answer: HttpServletRequest
Explanation: getRequestedSessionId() is a method on HttpServletRequest that returns the session id requested by the
client.

Q4 — Thread method that yields resources when called

Which method gives up CPU/resources when called on a thread?


Options: join / sleep / wait / yield

Correct answer: yield


Explanation: [Link]() hints scheduler to give other threads opportunity to run; sleep/wait block but for different
reasons; join waits for another thread.

Q5 — Static vs instance method invocation (OCR-fixed)

Given: class Test { static void A() {} void B() {} } Which is correct?
Options: Test.B() valid / Method A() can directly call B() / Method B() can directly call A() / None

Correct answer: Method B() can directly call A()


Explanation: An instance method B() can call static method A() directly; a static method cannot call instance methods
without an instance; Test.B() is invalid.

Q6 — Serializable inheritance

If Animal implements Serializable and Dog extends Animal, which is true?


Options: Dog object is not serializable / Dog object is serializable / Animal object is not serializable / None

Correct answer: Dog object is serializable


Explanation: Serialization status is inherited; subclass instances are serializable if superclass implements Serializable.

Q7 — Default float array value

What is the output of: float f[] = new float[5]; Object obj = f; [Link](f[0]);
Options: Compilation Error / Runtime Exception / 0.0 / 0

Correct answer: 0.0


Explanation: Primitive float array elements default to 0.0f.

Q8 — Iterator + modification behavior

Given code that creates a List, obtains an Iterator, iterates with [Link]() and inside loop calls [Link](5): which
happens?
Options: compiles and runs / compiles but throws ConcurrentModificationException / infinite loop / code will not compile

Correct answer: This code would compile but would throw ConcurrentModificationException at runtime.
Explanation: Modifying a Collection structurally while iterating with its Iterator (other than via [Link]()) triggers
ConcurrentModificationException.

Q9 — Starting a dead thread

If we try to invoke start() on a dead (already terminated) thread, what happens?


Options: becomes Runnable again / becomes Running again / not come alive but no exception / runtime exception

Correct answer: runtime exception


Explanation: Attempting to start a thread more than once throws IllegalThreadStateException at runtime.

Q10 — CMP 2.0 abstract-schema-name use


What is the use of abstract-schema-name in a CMP 2.0 entity bean deployment descriptor?
Options: indicates bean class name / specifies DB table / specifies schema identifier for EJB-QL / none

Correct answer: It specifies the schema identifier that will be used in the EJB-QL.
Explanation: abstract-schema-name provides the abstract schema name referenced in EJB QL.

Q11 — EJB transaction type (nested/distributed)

Two session beans: Hello1 updates DB A and B; Hello2 updates DB B only. Is this supported by EJB?
Options: nested tx not supported / nested supported / distributed supported / not distributed and not supported

Correct answer: This is an example of distributed transactions and will be supported by EJB.
Explanation: Operations spanning multiple transactional resources (multiple DBs) are handled as distributed (XA)
transactions coordinated by the container if configured.

Q12 — Java 9 Map method added

Which method was added to Map in Java 9?


Options: static [Link](K,V,...) / Map ofMap(...) / Both / None

Correct answer: static Map of(K k1, V v1, ...)


Explanation: Java 9 introduced [Link](...) factory methods to create immutable maps.

Q13 — JSP methods that cannot be overridden

Which method cannot be overridden in a JSP page?


Options: getParameter() / jspInit() / jspDestroy() / None

Correct answer: getParameter()


Explanation: getParameter is part of ServletRequest; jspInit() and jspDestroy() map to lifecycle methods and are allowed in
JSP-derived servlet code; getParameter is provided by the request object, not to be overridden via JSP method.

Q14 — Spring interface for registering externally created objects

Which Spring interface provides mechanism to register objects created outside container?
Options: DefaultListableBeanFactory / AutowireCapableBeanFactory / SimpleBeanFactory / StaticBeanFactory

Correct answer: AutowireCapableBeanFactory


Explanation: AutowireCapableBeanFactory supports configuring and autowiring externally created bean instances.

Q15 — Best connection pool for Hibernate (typical answer)

Which connection pool is best for Hibernate?


Options shown: c3p0 / p3c0 / t3do / 14do

Correct answer: c3p0


Explanation: c3p0 is a commonly recommended connection pool historically used with Hibernate (others include HikariCP,
DBCP).

Q16 — OOP concept to hide information

Which is used to hide information in OOP?


Options: [Link] [Link] [Link] [Link] with combinations

Correct answer: A,c (Encapsulation and Abstraction)


Explanation: Encapsulation hides internal state; abstraction hides implementation details.

Q17 — Indexed lookup faster on ArrayList vs LinkedList


For lookup of indexed elements, ArrayList is more efficient than LinkedList. True/False

Correct answer: True


Explanation: ArrayList provides O(1) random access; LinkedList requires traversal O(n).

Q18 — Java 8 feature to create work-stealing thread pool

Which feature lets create work-stealing thread pool?


Options: workPool / threadPool / work ThreadPool / newWorkStealingPool

Correct answer: newWorkStealingPool


Explanation: [Link]() creates a ForkJoinPool-based work-stealing pool.

Q19 — Purpose of Optional class in Java 8

What is Optional?
Options: avoid null checks / avoid NPE / represent optional values / bounded collection / All of above

Correct answer: It is used to represent optional values that either exist or do not exist.
Explanation: Optional models presence/absence of a value; it helps avoid null checks and reduce NPEs but principal
definition is representing optional values.

Q20 — Features introduced in Java 8

Which features were introduced in Java 8?


Options: Lambda Expressions / Default Methods / Method parameter reflection / Java Platform Module System / A,B,C

Correct answer: A, B and C


Explanation: Java 8 added lambdas, default methods, and parameter reflection; JPMS arrived in Java 9.

Q21 — Return type of a lambda expression

What is the return type of a lambda expression?


Options: void / Object / Function / String

Correct answer: Depends on context (the correct model answer from given options: Function)
Explanation: Lambda has the type of the target functional interface; often modeled by [Link] when
appropriate. (From provided choices, "Function" is the best fit.)

Q22 — Collection of type List can contain:

Options: String types / only CharSequence types / both String and CharSequence types / any Object

Correct answer: This collection can contain both String and CharSequence types
Explanation: String implements CharSequence, so both String and other CharSequence implementations can be added.

Q23 — True statement about JNDI in EJB concepts

Options: JNDI is a directory like LDAP / JNDI only provided by EJB container / JNDI offers location transparency / JNDI can
read but not write objects

Correct answer: JNDI offers location transparency


Explanation: JNDI provides location transparency for naming and directory lookup; it's not limited to EJB containers and is
not itself a directory server.

Q24 — Classes required in EJB 3.0 entity bean


Which classes are required? (A PrimaryKey class; B Remote/Local Bean class; C Remote/Local Home Interface; D
Remote/Local Business Interface; E single entity class)

Correct answer: Only E (a single entity class)


Explanation: EJB 3 uses POJO entity classes with JPA annotations; home and remote/home interfaces are not required.

Q25 — For an interface to act as remote interface

What should be done? A) must extend [Link] B) Each method must declare RemoteException

Correct answer: Both A and B


Explanation: RMI remote interfaces extend [Link] and remote methods declare RemoteException.

Q26 — findAncestorWithClass() functionality (JSP tag)

What does findAncestorWithClass() do?


Options: returns the nearest ancestor tag instance for the given class / immediate inner-most tag / returns a list of parent
tags / none

Correct answer: The method is used to get a reference to the nearest (deepest) enclosing Tag for the given Class object.
Explanation: [Link] finds the closest ancestor tag of the specified class.

Q27 — Defining bean for static inner class in XML

Which bean XML class declaration is correct for [Link]?


Correct answer:
Explanation: JVM name for static inner class uses in binary name; in Spring XML use fully qualified class name with.

Q28 — Benefits of Stream API

Options: functional style / parallel & pipelining / better performance / All / A and B

Correct answer: All of above


Explanation: Streams enable functional-style operations, pipelining and easy parallelization which can improve
performance.

Q29 — Pattern that creates families of related objects

Options: Abstract Factory / Factory / Adapter / None

Correct answer: Abstract Factory


Explanation: Abstract Factory provides interface for creating related objects without specifying concrete classes.

Q30 — Behavioral pattern allowing loose coupling where one class coordinates others

Options: Builder / Mediator / Memento / None

Correct answer: Mediator


Explanation: Mediator encapsulates how objects interact, promoting loose coupling.

Q31 — True statement about Abstract Factory and Singleton

Options listed; correct conclusion

Correct answer: An Abstract Factory pattern usually has multiple factory implementations
Explanation: Abstract Factory exposes interface for families; multiple concrete factories implement it. (Other statements in
options may be partially true but this is canonical.)
Q32 — Disadvantage of static factory method vs constructors (factory pattern)

Options given; which is disadvantage?

Correct answer: Static factory methods often require classes to have private constructors. Such classes cannot be
subclassed.
Explanation: That is a practical disadvantage when using static factory methods combined with non-public constructors.

Q33 — Is annotating classes with @Transactional sufficient?

Options: No / Yes / No, has to be added in configuration / It is necessary to add @EnableTransactionManagement

Correct answer: It is necessary to add @EnableTransactionManagement in the configuration


Explanation: @Transactional marks transactional boundaries, but enabling annotation-driven transaction support is
required in config (or XML equivalent).

Q34 — Correct use of @Autowired in controller (reconstructed)

Correct pattern: annotate the dependency field or constructor with @Autowired and declare it as a bean; e.g.:

@Controller @RequestMapping("/student-module") public class StudentController { @Autowired private StudentManager


leader;

@RequestMapping(value="/getAllStudents", method=[Link]) public String getAllStudents(Model model) {


[Link]("students", [Link]()); return "studentsListDisplay"; } }

Explanation: Use @Autowired on the dependency field (or constructor) and @RequestMapping on the handler method.

Q35 — Application logic that spans multiple application objects

Options: Tier / Layer / Cross cutting concern / None

Correct answer: Cross cutting concern


Explanation: Logic that spans multiple modules (e.g., logging, security) is called cross-cutting concern.

Q36 — Hibernate mapping file extension

Which extension is used for hibernate mapping file?


Options: .hbn / .hibernate / .[Link] / [Link]

Correct answer: .[Link]


Explanation: Hibernate mapping files are typically named *.[Link].

Q37 — Statements about uniqueness and object identity in DB (Hibernate)

S1: rows represent objects and must be unique; S2: two objects can have same attribute values; S3: system must
distinguish them. Which correct?

Correct answer: All


Explanation: S1 is true (IDs), S2 is possible (two objects with equal attributes), S3 is required to distinguish objects via
primary keys.

Q38 — All mapping files in Hibernate are referred from:

Options: context / server / Hibernate configuration file / none


Correct answer: Hibernate configuration file
Explanation: [Link] (or programmatic config) references mapping files.

Q39 — Interface that helps keep Hibernate apps portable across environments

Options: Query / Session / Transaction / None

Correct answer: Session


Explanation: Session is the main interface for interaction; Transaction and Query are important too but Session is core for
portability across environments.

Q40 — REPL full form

Correct answer: REPL — Read-Eval-Print Loop


Explanation: Standard expansion for REPL.

Q41 — Meaning of @Deprecated annotation

Options: usage may lead to errors / may be incompatible in future / both / none

Correct answer: Both Option 1 and 2


Explanation: @Deprecated indicates API should not be used and may be removed/changed in future and its use can cause
issues.

Q42 — Which describes failedStage() of CompletableFuture (Java 9+)

Options:

• Returns a new incomplete CompletableFuture of the type to be returned by a CompletionStage method.


• Returns a new CompletableFuture which is already completed with the given value.
• Returns a new CompletionStage which is already completed with the given value and supports only
CompletionStage methods.
• Returns a new CompletionStage which is already completed exceptionally with the given exception and supports
only CompletionStage methods.

Correct answer: Returns a new CompletionStage which is already completed exceptionally with the given exception and
supports only the methods present in interface CompletionStage.
Explanation: failedStage (or similar utility) returns an exceptionally completed CompletionStage; the best matching choice
describes an already exceptionally completed CompletionStage.

Q1
Which of the following method is used to delete all the messages in a queue?

1. delete

1. remove

1. redo

1. purge

Answer: D) purge
Explanation: Message broker UIs and APIs commonly use "purge" to clear all messages from a queue.
Q2
Active Message Queue also supports priority consumption (using priority queue) so that high priority messages are
consumed before low priority message. Which of the following attribute sets a priority queue in place for ActiveMQ?

1. prioritizedMessages="true"

1. prioritizedMessages="false"

1. [Link]=1

1. [Link]=2

Answer: A) prioritizedMessages="true"
Explanation: ActiveMQ transport/connector and destination configuration use prioritizedMessages attributes to enable
priority-based dispatching.

Q3
In Deployment descriptor which sub element in tag helps in declaring a listener?

1. servlet

1. servlet-mapping

1. listener-name

1. listener-class

Answer: D) listener-class
Explanation: In [Link], names the listener implementation; is optional meta, but is required to declare the listener class.

Q4
For the URL [Link] which HTTP request gets generated by a browser?

1. GET

1. POST

1. HEAD

1. NET

Answer: A) GET
Explanation: Browsers use HTTP GET to retrieve a page by URL.

Q5
Which one of the following is equivalent to line 1 in this interface?
interface ITest1 { void show(); // Line 1 }

1. public final not final

1. public abstract not final

1. static abstract not final

1. hide data not final


Answer: B) public abstract not final
Explanation: Prior to default/private methods, interface methods are implicitly public and abstract.

Q6
putIfAbsent(key, value) is a part of which collection?

1. ConcurrentMap

1. HashMap

1. ArrayList

1. SortedMap

Answer: A) ConcurrentMap
Explanation: putIfAbsent is defined on ConcurrentMap (and implemented by ConcurrentHashMap).

Q7
The field in an interface is implicitly defined as

1. static

1. public

1. final

1. All of the above

Answer: D) All of the above


Explanation: Interface fields are implicitly public, static, and final.

Q8
Which of the following is used to achieve runtime polymorphism?

1. Method overriding

1. Method overloading

1. Return type

1. Virtual function

Answer: A) Method overriding


Explanation: Runtime polymorphism in Java is achieved via overriding (dynamic dispatch).

Q9
What will be the output of the following code? class DemoCode { public static void main(String arg[]) { byte b = 1; b += 1;
[Link](b); } }

1. 1

1. 2

1. 12

1. None of these
Answer: B) 2
Explanation: Compound assignment b += 1 includes an implicit cast; result is byte 2.

Q10
Which of the following interface contains hasPrevious() method?

1. Iterator

1. ListIterator

1. Both

1. None of the above

Answer: B) ListIterator
Explanation: ListIterator adds bidirectional navigation (hasPrevious/previous).

Q11
As per EJB concepts, in a primary key class, what is the purpose of the equals() and hashCode() methods?

1. ... (long option describing store/get error handling)

1. ... (description about PKs filter hashCode)

1. equals() returns boolean indicating equality so container uses hashCode to check PK implementation

1. same as C (duplicate)

Answer: C) The equals() method returns a boolean indicating if the object is equal so that the hashCode() is used by the
container to check the actual implementation for PK.
Explanation: For primary key classes consistency of equals() and hashCode() is required so containers and collections can
correctly manage identity.

Q12
As per EJB concepts, is it possible to have a static initializer block in EJB?

1. It's not possible to have static initializer block in EJB

1. It is technically possible but it is not supported

1. Compiler would not complain but runtime exception would be thrown

1. None of the given options

Answer: B) It is technically possible but it is not supported


Explanation: Static initializers are Java language features and compile, but many EJB containers discourage static
initialization because of classloading and lifecycle constraints.

Q13
Which of the following method is added to Map in Java 9?

1. static [Link](K1,V1,K2,V2,K3,V3)

1. [Link](K1,V1,K2,V2,K3,V3)

1. Both Option 1 and 2


1. None

Answer: C) Both Option 1 and 2


Explanation: Java 9 added factory methods [Link](...) and [Link](...) for small immutable maps.

Q14
Which of the following method if called from a JSP page would produce an unpredictable result?

1. do_post()

1. [Link]()

1. [Link](0)

1. none of the above

Answer: C) [Link](0)
Explanation: Calling [Link] terminates the JVM (container), producing unpredictable/undesired behavior; do_post
isn't a JSP method name and [Link] is safe (prints to server console).

Q16
What does [Link](Query).scroll() return?

1. ListResultSet

1. ResultSet

1. ScrollableResultSet

1. ScrollableResult

Answer: D) ScrollableResult
Explanation: In Hibernate, [Link]() returns a ScrollableResults or similar scrollable result abstraction; in API terms it is
often referred to as ScrollableResults/ScrollableResult.

Q17
Which of the following can be used in place of 'Overloading'?

1. Virtual polymorphism

1. Transient polymorphism

1. Ad hoc polymorphism

1. Pseudo polymorphism

Answer: C) Ad hoc polymorphism


Explanation: Overloading is an example of ad-hoc polymorphism.

Q18
What does SAM stand for in context of Functional Interface?

1. Single Abstract Marker

1. Simple Abstract Marker

1. Single Abstract Method


1. Simple Abstract Markup

Answer: C) Single Abstract Method


Explanation: Functional interfaces have a single abstract method (SAM).

Q19
Select the single most appropriate description of Lambda expression from the following:

1. Java syntax for defining mathematical expression

1. A way of introducing inline delegate (C# style)

1. A way of creating code as data, e.g., passing functionality as a parameter

1. None of the above

Answer: C) A way of creating code as data, for example passing some functionality as a parameter
Explanation: Lambdas let you pass behavior as values matching functional interfaces.

Q20
Which of the following data structures is likely to be used by a HashMap to handle collisions?

1. Linked List

1. Stack

1. Queue

1. Binary Tree

Answer: D) Binary Tree (and Linked List historically)


Explanation: HashMap in modern JDKs uses buckets that are linked lists which convert to balanced trees (red-black) when
collisions grow beyond a threshold.

Q21
What are the two types of Streams offered by Java 8?

1. Parallel and Random

1. Sequential and Random

1. Sequential and Parallel

1. Random and Performance

Answer: C) Sequential and Parallel


Explanation: Streams can be sequential or parallel.

Q22
How can the Advanced Encryption Standard (AES) be disabled using the Java VM Option?

1. Using -XX:+UseAES and -XX:+HasAESIntrinsics

1. Using -XX:-UseAES-disable and -XX:-HasAESIntrinsics-disable

1. Using -XX:-UseAES-disable and -XX:+HasAESIntrinsics-disable


1. Using -XX:+UseAES-disable and -XX:-HasAESIntrinsics-disable

Answer: C) Using -XX:-UseAES-disable and -XX:+HasAESIntrinsics-disable


Explanation: To disable features the -XX:-Flag form is used; combined flag names depend on JVM implementation. (Use the
proper flag syntax for your JVM.)

Q23
Which of the following is not introduced with Java 8?

1. Stream API

1. Lybdaum (Lambda)

1. Removal of PermGen

1. Serialization

1. Lambda Expressions

Answer: C) Removal of PermGen


Explanation: Removal of PermGen (migrated to Metaspace) is a JVM change in Java 8, but it’s not a Java language feature;
however in context the intended “not introduced” answer is ambiguous—classic language features (Stream API, Lambda)
are Java 8 features; PermGen removal is a VM change, not a language feature.

Q25
Which of the following statements about stubs and skeletons is true?

1. Stubs and skeletons are implemented by the developer

1. Stubs and skeletons are generated automatically by the RMI compiler

1. Stubs and skeletons are a part of session and entity beans

1. None of the given options

Answer: B) Stubs and skeletons are generated automatically by the RMI compiler
Explanation: RMI uses generated stubs (client-side) and previously skeletons (server-side) from rmic or dynamic proxy
generation.

Q26
As per EJB concepts in every EJB JAR file, which of the following options must be included?

1. Stubs for the EJBHome and EJBObject interface, A deployment descriptor

1. The JAR Manifest file, The EJB Home interface

1. A deployment descriptor, The EJB home interface

1. The JNDI context, The JAR Manifest File

Answer: C) A deployment descriptor, The EJB home interface


Explanation: Historically EJB JARs must include the deployment descriptor and EJB interfaces; exact requirements vary by
EJB version and packaging.

Q27
What is the difference between [Link]() and [Link]()?
1. forward dispatches internally; sendRedirect issues a client redirect and changes URL (correct)

1. reversed

1. forward can forward outside container

1. None of these

Answer: A) [Link] forwards the request on server; [Link] sends a redirect


response to client changing URL.
Explanation: forward is server-side, sendRedirect is client-side new request.

Q29
As per design patterns concepts, which structural pattern uses shared objects to minimize memory?

1. Flyweight

1. Singleton

1. Prototype

1. None

Answer: A) Flyweight
Explanation: Flyweight shares fine-grained objects to reduce memory footprint.

Q30
Which design patterns address decoupling senders and receivers with different trade-offs?

1. Chain of responsibility

1. Command

1. Observer

1. All of the given options

Answer: D) All of the given options


Explanation: Each decouples senders/receivers in different ways.

Q31
Which of the following is not a valid method declaration within an interface in Java?

1. public String show();

1. abstract String show();

1. final String show();

1. String show();

Answer: C) final String show();


Explanation: Interface methods cannot be declared final (prior to Java 8 defaults); method declarations in interfaces are
implicitly public and abstract; final is not allowed.

Q32
Which of the following connection pools is best for Hibernate?
1. c3p0

1. proxool

1. DBCP

1. HikariCP

Answer: D) HikariCP (modern best choice)


Explanation: Historically c3p0 and DBCP were popular; today HikariCP is preferred for performance and stability.

Q33
Which of the following is not introduced in Java 9?

1. MultiRelease JAR

1. Private Methods in Interfaces

1. Lambda expressions

1. HTML5 based java documentation

Answer: C) Lambda expressions


Explanation: Lambdas were introduced in Java 8; Java 9 introduced module system and Multi-Release JARs; private
methods in interfaces arrived in Java 9.

Q34
Answer the following questions based on your knowledge of Hibernate. Which of these is a tag of the class
[Link]?

1. DTD

1. Mapping files

1. JDBC connection configuration

1. Mapping files and JDBC connection configuration

Answer: D) Mapping files and JDBC connection configuration


Explanation: [Link] commonly contains JDBC connection properties and mapping file references.

Q35
Which of the following operations is not supported by HQL?

1. Create

1. Insert

1. Select

1. None of the above

Answer: B) Insert (HQL does not support general INSERT SELECT into — HQL supports INSERT ... SELECT with limitations;
DML support is limited)
Explanation: HQL focuses on SELECT and UPDATE/DELETE for entities; INSERT support is limited compared to SQL.
Q36
Assuming Cat, Apple, Bears, Dogs, Sparrows, Pigeons are persistence classes, which HQL returns all persistent objects of a
Hibernate application?

1. from pCat as cat

1. from exApple as apple, exBears as bears

1. from [Link] obj

1. none of the above

Answer: D) none of the above


Explanation: Each entity must be queried by its mapped entity name; there is no single HQL that returns all entities.

Q37
Which of the following correctly describes the ifPresentOrElse() method of Optional class?

1. If a value is present it returns a sequential Stream containing only that value, otherwise returns an empty Stream.

1. If a value is present, performs the given action with the value, otherwise performs the given empty-based action.

1. Both Option 1 and 2

1. None

Answer: B) If a value is present, performs the given action with the value, otherwise performs the given empty-based
action.
Explanation: ifPresentOrElse accepts a Consumer (action) and a Runnable (empty action).

Q38
Which of the following is not introduced in Java 9?

1. MultiRelease JAR

1. Private Methods in Interfaces

1. Lambda expressions

1. HTML5 based java documentation

Answer: C) Lambda expressions


Explanation: Lambdas are Java 8.

Q39
Which of the following data structures is likely to be used by a TreeMap?

1. Binary Search Tree

1. Hash Table

1. Red Black Tree

1. Array

Answer: C) Red Black Tree


Explanation: TreeMap is implemented as a Red-Black tree.
Q40
Which feature of Java 8 enables creating a work-stealing thread pool using all available processors?

1. workLoad

1. threadPool

1. workThreadPool

1. newWorkStealingPool

Answer: D) newWorkStealingPool
Explanation: [Link] creates a ForkJoinPool-based work-stealing pool.

Q41
One difference between Collection API and Stream API is that Streams can process infinite elements. True/False

• TRUE
• FALSE

Answer: TRUE
Explanation: Streams can be finite or infinite (e.g., using [Link] or iterate).

Q42
Which of the following is not a valid HTTP request method? (from earlier)

• GET / PUT / HEAD / RESUME (depending on earlier PDF) — common invalid method: RESUME or similar

Answer: RESUME (not an HTTP method)


Explanation: Standard HTTP methods do not include RESUME.

Q43
Which of the following is used to delete all messages in a queue? (duplicate Q1 earlier)

• Answer: purge (see Q1)

Q44
Which of the following is a correct statement about Process API in Java 9?

1. ProcessHandle class provides methods to check liveness

1. ProcessHandle has onExit method returning CompletableFuture

1. Both 1 and 2

1. None

Answer: C) Both 1 and 2


Explanation: ProcessHandle provides liveness checks and onExit returns CompletableFuture.

Q45
Which of the following is not a valid method declaration within an interface in Java?

1. public String show();

1. abstract String show();


1. final String show();

1. String show();

Answer: C) final String show();


Explanation: interface methods cannot be final; other forms are valid declarations (implicitly public/abstract).

Q46
Which of the following connection pools is best for Hibernate? (duplicate)
Answer: HikariCP (modern best choice; historically c3p0 also popular)

Q47
Which of the following is not introduced with Java 8? (duplicate)
Answer: Removal of PermGen (VM-level change) or if question expects language feature: Java Platform Module System
(Java 9) — check context.

Q48
Which of the following tags appear in [Link]?

• Answer: mapping files and JDBC connection configuration (see Q34)

Q49
Which of the following is not introduced in Java 9? (duplicate)
Answer: Lambda expressions (introduced in Java 8)

Q50
Which of the following are correct with regard to this code?
class Parent { void display(int i) { } }
class Child extends Parent { void display(int i) { } void display() {} }
Options about overriding/overloading etc.

Answer: Methods display(int) in Parent and Child are overriding; display() is an overload — so "The methods in lines ... are
overridden; ... overloaded" (choose the option that expresses that overriding occurs for display(int) and overloading for
display()).

Question 1

Which of the following is the method where @RequestMapping is used with headers?

Options:

1.@RequestMapping(value="/method4", headers="name=pankaj")

@ResponseBody

public String method4() {

return "method4";

@RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})

@ResponseBody

public String method5() {


return "method5";

2.@RequestMapping(value="/method4", headers="name=pankaj")

@ResponseBody

public void method4() {

return "method4";

@RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})

@ResponseBody

public String method5() {

return "method5";

3.@RequestMapping(value="/method4", headers="name=pankaj")

@ResponseBody

private String method4() {

return "method4";

@RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})

@ResponseBody

private void method5() {

return "method5";

Correct Answer: A

Explanation:

Spring allows header-based mapping using headers in @RequestMapping. The method should be public and return a valid
type. Option A correctly uses public methods with proper header syntax.
Question 2

Which of the following is a correct syntax for creating an embedded broker in Apache ActiveMQ?

Options:

[Link] broker = new BrokerService();

[Link]("tcp://localhost:61616");

[Link]();

[Link] broker = new BrokerService();

[Link]("tcp/localhost:61616");

[Link]();

[Link] broker = new BrokerService();

[Link]("tcp://localhost:61616");

[Link]();

[Link] broker = new BrokerService();

Correct Answer: A

Explanation:

The correct way to start an embedded ActiveMQ broker is to use addConnector() with a valid URI and then call start().

Question 3

Assuming that data must be protected from corruption, what can you add to the following code to ensure thread safety?

Code snippet:

private int data = 23;


public void increase(int amt) {

int x = data;

data = x + amt;

Options:

- Synchronize the increase() method

- Wrap a synchronized(this) block around the call to increase()

- The existing code will cause a runtime exception

- Synchronize the thread that runs the method

Correct Answer: A

Explanation:

Synchronizing the method ensures atomic access to the shared data field, preventing race conditions.

Question 4

Which of the following correctly describes the completedStage() method of the CompletableFuture interface?

Options:

- Returns a new incomplete CompletableFuture of the type to be returned by a CompletionStage method

- Returns a new CompletableFuture which is already completed with the given value

- Returns a new CompletionStage which is already completed with the given value and supports only those methods
present in interface CompletionStage

- Returns a new CompletionStage which is already completed exceptionally with the given exception and supports only
those methods present in interface CompletionStage

Correct Answer: C

Explanation:

completedStage() returns a CompletionStage that is already completed with a value and exposes only CompletionStage
methods.
Question 5

What is the output of the following code?

Code snippet:

public class SingletonPrototypeTest {

@Resource Singleton singletonOne;

@Resource Singleton singletonTwo;

@Resource Prototype prototype;

@Test

public void printValues() {

for (int i = 0; i < 2; i++) {

[Link]();

[Link]();

[Link]([Link]());

@Component class Singleton {

@Resource Prototype prototype;

void printValue() {

[Link]([Link]());

@Component

@Scope(BeanDefinition.SCOPE_PROTOTYPE)

class Prototype {}
Options:

- 4 times the same hash code

- 3 times same hash code and 1 different hash code

- 2 pairs of same hash code

- 4 distinct hash codes

Correct Answer: B

Explanation:

Prototype beans injected into singletons are instantiated once per injection. So unless explicitly fetched per call, the same
instance is reused, leading to repeated hash codes.

Question 6

Consider the following statements about Hibernate:

• R1: In the process of working with persisted objects, two additional interfaces are commonly used.
• R2: The Transaction interface lets you ensure that all operations on persisted objects occur in a transaction
supported by JDBC or JTA.
• R3: When using a transaction, any error between start and end will cause all operations to fail.
• R4: The Query interface lets you query the database for objects instead of relying solely on an object's identifier.

Options:

1. R1

1. R1 & R2

1. R1, R2 & R3

1. All of the above

Correct Answer: D) All of the above


Explanation:
All four statements are accurate descriptions of Hibernate’s behavior and interfaces. Transactions ensure atomicity, and
Query provides flexible retrieval.

Question 7

What is the output of the following code?

Code snippet:

try {
int x = 30 / 0;

} catch (ArithmeticException e) {

[Link]("Exception1");

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Exception2");

} catch (Exception e) {

[Link]("common");

[Link]("test");

Options:

1. Exception1 Exception2

1. Exception1 test

1. Exception1 common test

1. Exception1 Exception2 test

Correct Answer: B) Exception1 test


Explanation:
Division by zero throws ArithmeticException, which is caught by the first catch block. Then "test" is printed.

Question 8

What is servlet preloading (load-on-startup)?

Options:

1. A container initializes the servlet on startup

1. A container does not initialize the servlet until a request is received

1. The process of loading a servlet before a request comes

1. The process of loading a servlet at compile time

Correct Answer: A) A container initializes the servlet on startup


Explanation:
Setting in [Link] causes the servlet to be loaded and initialized when the server starts.

Question 9

What does the following JMS application do for the given class TestQueue?

Code snippet summary:


• Creates a connection
• Creates a session
• Gets a queue
• Creates a MessageConsumer
• Registers a TextListener

Options:

1. Fetches messages using synchronous delivery

1. Fetches messages using asynchronous delivery

1. Fetches messages using both synchronous and asynchronous delivery

1. Fetches messages using scheduled delivery

Correct Answer: B) Fetches messages using asynchronous delivery


Explanation:
Registering a listener with setMessageListener() enables asynchronous message consumption.

Question 10

What happens if a remote client invokes a method on an entity bean that has been removed?

Options:

1. A new entity bean will be created

1. [Link] will be thrown

1. [Link] will be thrown

1. None of the given options

Correct Answer: C) [Link] will be thrown


Explanation:
Calling a method on a removed entity bean results in an EJBException, indicating the bean no longer exists.

Question 11

As per EJB concepts, two session beans Hello1 and Hello2 are used. Hello1 updates databases A and B, Hello2 updates
only B. Is this supported by EJB?

Options:

1. This is an example of nested transactions, not supported by EJB

1. This is an example of nested transactions, supported by EJB

1. This is an example of distributed transactions and will be supported by EJB

1. This is not an example of distributed transactions and will not be supported


Correct Answer: C) This is an example of distributed transactions and will be supported by EJB
Explanation:
EJB supports distributed transactions across multiple resources using JTA/XA protocols.

Question 12

What will happen if a remote client invokes a method on an entity bean that has been removed?

Options:

- A new entity bean will be created in Java EE

- [Link] will be thrown

- [Link] will be thrown

- None of the given options

Correct Answer: C) [Link] will be thrown

Explanation:

When a method is invoked on a removed entity bean, the container throws an EJBException indicating that the bean no
longer exists.

Question 13

What is the motivation behind using the Command design pattern?

Options:

- To add responsibilities to individual objects

- To issue requests to objects without knowing anything about the request or the receiver

- To provide a uniform interface for traversing different aggregate structures

- To maintain consistency without tight coupling

Correct Answer: B) To issue requests to objects without knowing anything about the request or the receiver

Explanation:

The Command pattern encapsulates a request as an object, allowing parameterization and decoupling of sender and
receiver.

Question 14

Suppose we are creating a JMS application that sends a message to a queue. Which of the following code snippets correctly
creates a QueueSender and a TextMessage?
Options:

QueueSender sender = [Link](t);

TextMessage msg = [Link]();

QueueSender sender = [Link](t);

TextMessage msg = [Link]();

TestMessage msg = [Link]();

QueueSender sender = [Link](t);

QueueSender sender = [Link](t);

TextMessage msg = [Link]("Hello");

Correct Answer: A)

Explanation:

The standard JMS API uses createSender() and createTextMessage() methods on QueueSession to create a sender and
message.

Question 15

Which of the following statements about Hibernate object identity and uniqueness is correct?

Statements:

- S1: When Hibernate places an object in the database, each row must be unique because rows represent specific objects.

- S2: It is possible for two objects in the system to have the same attribute values.

- S3: If this occurs, the system needs to distinguish the objects in the database.
Options:

- S1

- S1 & S2

- All of the above

- None of these

Correct Answer: C) All of the above

Explanation:

Hibernate uses primary keys to ensure uniqueness. Two objects may have identical attributes but must be distinguishable
via their identifiers.

Question 16

Suppose we are creating a JMS application that receives messages from a queue. Which of the following listener
implementations is correct?

Options:

class MyListener implements MessageListener {

public void onMessage(Message m) {

try {

TextMessage msg = (TextMessage) m;

[Link]("Message received: " + [Link]());

} catch (JMSException e) {

[Link](e);

class MyListener {

public void onMessage(Message m) {

TextMessage msg = (TextMessage) m;


[Link]("Message received: " + [Link]());

class MyListener {

public void onMessage(Message m) {

// no casting

class MyListener implements Runnable {

public void run() {

// not a message listener

Correct Answer: A)

Explanation:

To receive messages asynchronously, the listener must implement MessageListener and override onMessage() properly.

Question 17

Which of the following best describes the behavior of @RequestMapping when used with headers?

Options:

- Accepts header presence and value match using headers="name=foo"

- Requires array syntax only: headers={"name=foo","id=1"}


- Cannot be used with @ResponseBody

- Only accepts header existence, not value match

Correct Answer: A) Accepts header presence and value match using headers="name=foo"

Explanation:

Spring allows header-based mapping using either a single string or array syntax. You can match both header presence and
specific values.

Question 18

What is the correct behavior when a prototype-scoped bean is injected into a singleton-scoped bean in Spring?

Options:

- All hash codes printed will be the same

- Some hash codes will be the same, some different

- All hash codes will be different

- Injection will fail

Correct Answer: B) Some hash codes will be the same, some different

Explanation:

Prototype beans injected into singletons are instantiated once per injection. Unless explicitly fetched per call, the same
instance is reused.

Question 19

What output will the following code produce when an ArithmeticException is thrown?

Code snippet:

try {

int x = 30 / 0;

} catch (ArithmeticException e) {

[Link]("Exception1");

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Exception2");

} catch (Exception e) {
[Link]("common");

[Link]("test");

Options:

- Exception1 Exception2

- Exception1 test

- Exception1 common test

- Exception1 Exception2 test

Correct Answer: B) Exception1 test

Explanation:

The first matching catch block executes. After handling the exception, the program continues to print "test".

Question 20

Which of the following best describes the purpose of the @EnableWebSecurity annotation in Spring?

Options:

- Enables web security features in the application

- Enables MVC features

- Registers servlet filters only

- Is sandbox-specific and deprecated

Correct Answer: A) Enables web security features in the application

Explanation:

@EnableWebSecurity activates Spring Security’s web security support and integrates it with Spring MVC.

Question 21

Which of the following correctly describes the behavior of the TestQueue class in a JMS application that registers a
listener?

Options:

- Fetches messages using synchronous delivery


- Fetches messages using asynchronous delivery

- Uses both synchronous and asynchronous delivery

- Uses scheduled delivery

Correct Answer: B) Fetches messages using asynchronous delivery

Explanation:

Registering a MessageListener with setMessageListener() enables asynchronous message consumption.

Here’s the list of all questions you asked today (30th Sept 2025) along with the answers I gave:

---

1.

Q: Which of the following is true about ActiveMQ? Large files cannot be sent over ActiveMQ. ActiveMQ does not support
clustering. In Apache, ActiveMQ currently, two brokers cannot operate on the same set of databases.

A: In Apache ActiveMQ, currently, two brokers cannot operate on the same set of databases.

---

2.

Q: Answer the below question based on servlet concept. DAS method is used to specify before any lines that used to print
writer. Options: SetPageType, SetContextType, SetContextType, SetResponseType.

A: SetContentType (you had typo in options, correct is setContentType).

---
3.

Q: The field in an interface is implicitly defined as static, public, final, or all of the above.

A: All of the above.

---

4.

Q: Put if absent key or value is part of which collection? Concurrent Map, AbsNet, Argonist, Shorted Map

A: ConcurrentMap.

---

5.

Q: As per EJB concept, is it possible to have Static Initializer Rollout in EJB?

A: No, EJB does not allow static initializers because they break container-managed lifecycle and portability.

---

6.

Q: What will happen if a remote client invokes a method on EntityWin on which EJVRemove has been called?
A: It will throw NoSuchObjectException (or similar) since the entity has been removed and the reference is invalid.

---

7.

Q: Lambda expressions enable Java to provide features that look like functional programming, but do not guarantee
immutability of the data they are processing, true or false.

A: True.

---

8.

Q: As per design pattern concept, which of the following structured patterns use shared objects that can be used in
multiple contexts simultaneously so as to minimize memory use? Options are Lie, Weak, Singleton, Prototype, None of the
given options.

A: Flyweight pattern (your options didn’t have it, so correct is None of the given options).

---

9.

Q: Choose the correct option. All mapping files in Hibernate are referred from options as Context, Server, Hibernate
configuration file, None of the above.

A: Hibernate configuration file.


---

10.

Q: In which version of Java Diamond operator was introduced?

A: Java 7.

---

11.

Q: How implementations the context-conflict location used in SYNC MDC

A: You asked this but didn’t clarify further, so I didn’t provide a direct answer yet.

---

Do you want me to combine these into a clean Q&A sheet (like for revision), or just keep them in the raw asked-answer
sequence as above?

Here is a summary of all the questions and answers from our session today:

1. Q7: If we try to invoke start() method on a dead thread, then which of the following will happen?

A: D: Runtime exception will occur.

2. Q8: What would be output of below code? (try-catch-finally with returns)

A: C: 3
3. Q13: Which of the following method is added to Map in Java 9?

A: D: None

4. Q14: What are the events in jsp page?

A: B: jspLoad()

5. Q15: Spring Web Services provides server-side email handling feature by implementing X class and uses Y to send
response.

A: A: X: MailMessageReceiver Y: PCP3

6. Q16: Which of the following is credit worthy for pulling, parsing and compiling the mapping documents into a format
that Hibernate uses internally?

A: A: Configuration object.

7. Q17: Which of the following is used to hide information in object oriented programming?

A: A: Encapsulation

8. Q18: Consider an instance of a collection of type List<CharSequence>

A: C: This collection can contain both String and CharSequence type.

9. Q20: It makes sense to replace Lambda expressions with Method References

A: D: Depends on the whether the lambda expression has other operations in addition to the value.

10. Q21: A Lambda expression can be passed as an argument to a method where a functional interface is expected...

A: A: TRUE

11. Q22: How is lambda expression represented by the JVM at runtime?

A: B: As a dynamically created lambda object with a dynamically created type at runtime


12. Q23: Select the correct option for following code snippet: ([Link] = 0 - { ... })

A: A: Code will encounter compilation error

13. Q24: When will the finally block not be implemented?

A: C: When [Link]() is called

14. Q25: As per EJB concepts, which of the following statements about JNDI (Java Naming and Directory Interface) is
[correct]:

A: C: JNDI offers location transparency.

15. Q26: As per EJB concepts, under what transaction attribute settings, will the EJB container throw an exception upon
invoking getRollbackOnly() method...?

A: C: Never

16. Q29: Following are benefits of using Stream API:

A: D: All of above

17. Q31: As per design patterns concepts, which of the following structural patterns uses shared objects... to minimize
memory use?

A: B: Flyweight

18. Q32: ...Which of the following design patterns would you use to ensure that same JFrame instance (J2) is shown every
time...?

A: C: Singleton

19. Q33: If two classes are defined by a composition relation, which of the following statements is true?

A: A: Composite class has components close as collaborative

20. Q34: Which of the following statements about State design pattern is/are true?
A: B: Both B and C

21. Q36: In Spring Framework's declarative transaction implementation, is it sufficient to annotate the classes with the
@Transactional annotation?

A: D: It is necessary to add @EnableTransactionManagement in the configuration

22. Q40: Global transactions are managed by an application server using which of the following?

A: C: JTA

23. Q41: What does Spring use to provide declarative transaction management without using EJB?

A: D: AOP

24. Q42: Which of the following is not supported in Spring MVC?

A: D: JavaDaoSupport

25. Q43: Which of the following methods uses RequestMapping with a class?

A: C: @Controller @RequestMapping("/home") public class HomeController { }

26. Q44: Hibernate applications work more efficiently with:

A: C: both of the above (Simple java classes & plain old java objects)

27. Q45: ...which of the following HQL statements returns all persistent objects of a Hibernate application?

A: D: none of the above

28. Q48: What REPL stands for?

A: A: Read Eval Print Loop

29. Q46: Which is a correct statement about try-with-resources statement in Java?

A: D: All of the above


30. Q47: Consider the following statements about Hibernate interfaces (R1, R2, R3, R4)...

A: D: All of the above

Question 5 What will be the outcome when the given code is compiled and run? class qq361 public static void main(String
as m1(null): 1 static void m1(Object (1) [Link]("Object i1" static void m1(String 11)( [Link]("String
11):

ChatGPT said:

Got it Let’s carefully analyze your code snippet.

The code (with proper formatting) looks like this:

class qq361 {

public static void main(String as[]) {

m1(null);

static void m1(Object o) {

[Link]("Object");

static void m1(String s) {

[Link]("String");

Explanation:

• In main, we call m1(null).


• Java checks which overloaded method matches null.
• Both m1(Object) and m1(String) can take null as an argument.
• But String is more specific than Object.
• Hence, the compiler chooses m1(String).
Correct Answer:

The program will compile successfully and print:

String

Do you want me to also explain what would happen if there were two unrelated reference types (e.g., m1(String) and
m1(Integer))?

You said:

ChatGPT said:

I can see the question on your screen. Let’s analyze it carefully.

The question is:

class Test {

public static void main(String args[]) {

Thread t = [Link]();

[Link](t);

}
}

Step-by-step:

1. [Link]() → returns a reference to the currently executing thread, which is the main thread when
the program starts.
2. Printing a Thread object calls its toString() method.
3. Default format of [Link]() is:
4. Thread[<thread-name>,<priority>,<thread-group-name>]

For the main thread:

o thread-name = main
o priority = 5 (default priority)
o thread-group-name = main

So the output is:

Thread[main,5,main]

Correct Answer:

Thread[main,5,main]

Do you want me to also solve all such thread-based output questions quickly for you (so you can save time in the test)?

You said:
ChatGPT said:

Thanks for sharing the image Let’s carefully rewrite and analyze the code in it:

public class Test extends Thread {

public void start() {

[Link]("Start Method");

public void run() {

[Link]("Run method");

public static void main(String[] args) {

Test t1 = new Test();

Test t2 = new Test();


[Link]();

[Link]();

Key points:

1. Normally, calling start() on a thread object invokes the JVM’s internal [Link]() which eventually calls run()
in a new thread.
2. But here, start() is overridden with a normal method that only prints "Start Method".
This means the thread will never actually start in a new thread.
3. In main, the code calls [Link](); and [Link](); directly.
o This is not multithreading — just normal method calls.
o So it will execute sequentially on the main thread.
4. Both calls print "Run method".

Correct Output:

Run method

Run method

Do you want me to also explain what the output would be if [Link](); and [Link](); were called instead of run() in this
program?

You said:
ChatGPT said:

I can read the code in your screenshot. Let’s rewrite it properly:

public static void main(String args[]) {

try {

RandomAccessFile raf = new RandomAccessFile("[Link]", "r");

byte[] b = new byte[1000];

[Link](b, 0, 1000);

catch(IOException e) {

[Link]("File not found");

[Link]([Link]());

[Link]();

catch(FileNotFoundException e) {
[Link]("IO Error");

[Link]([Link]());

[Link]();

Analysis:

1. Problem with catch order:


o FileNotFoundException is a subclass of IOException.
o In Java, the more specific catch block must come before the more general one.
o Here, catch(IOException e) is before catch(FileNotFoundException e).
o The compiler sees that the second catch block (FileNotFoundException) is unreachable code.
2. This leads to a compile-time error:
3. error: exception FileNotFoundException has already been caught

Correct Answer:

Compile time error

Do you want me to also fix the code and explain what the output would be if the order of catch blocks were reversed?

You said:

Not a correct signature for method overloading of void fun Void fun( int a) Int fun (int a) Void fun(int a , int b) All

ChatGPT said:

Good question Let’s break this down.

Method overloading means:

• Same method name


• Different parameter list (type, number, or order of parameters)
• Return type alone does not matter

Options:

1. void fun(int a) valid method.


2. int fun(int a) NOT valid if combined with option 1, because only return type differs (parameters are the
same). This is not overloading.
3. void fun(int a, int b) valid method (different parameter list).
4. All incorrect, since option 2 makes conflict.
Correct Answer:

Int fun(int a)

This one is not a correct signature for method overloading.

Would you like me to also give you a quick rule-of-thumb table so you can instantly spot valid vs invalid overloads in your
test?

You said:

As per EJB concepts, a session bean WageBean implements Wage interface as shown in the following code snippet. Which
of the given statements about the following code snippet is correct? @Stateless @Remote @Local public class WageBean
implements Wage public float calculateWage() (//do something) public float calculate Tax() //do something)

ChatGPT said:

Got it Let’s carefully analyze your EJB question.

Code snippet (formatted):

@Stateless

@Remote

@Local

public class WageBean implements Wage {

public float calculateWage() {

// do something

public float calculateTax() {

// do something

EJB Concepts:
1. Session Bean:
o @Stateless marks this class as a stateless session bean.
2. Business Interfaces:
o A bean can implement local or remote business interfaces.
o If both @Remote and @Local are specified, the same interface (Wage) is considered both local and
remote.
3. Interface Contract:
o Any method exposed in the interface (Wage) must be implemented in the bean.
o If the bean defines extra methods (like calculateTax() here) that are not part of the interface, those
methods are not accessible to clients through the business interface.
o Such methods can only be used internally within the bean.

Correct Statement:

The method calculateWage() is exposed to clients (since it is defined in the Wage interface).
The method calculateTax() is not available to clients through the business interface, as it is not part of Wage.

Do you want me to phrase the answer in MCQ-style (exam-ready statement) for you?

You said:

Select an option 0 The guen code is correct the annotations should be on new lines. A buen cannot be defined as @Remote
and @Local both Alean coat be defined as @Stateless or @Local. Give above answer

ChatGPT said:

Thanks for sharing the options

Based on EJB rules:

• A bean can be both @Remote and @Local → that is valid.


• @Stateless, @Local, @Remote annotations can all be applied together.
• Saying annotations must be on new lines is wrong (Java allows multiple annotations on the same line).
• A bean can definitely be @Stateless and @Local.

Correct Answer:

The given code is correct

Which of the following method is added to Map in Java 9? static Man of ki, Vvi, Kk Vv2, Kk3, Vv3) Map of Map/K KT, Vvt.
Kk2, Vv2, Kk3, Vv3) Both Option 1 and 2

ChatGPT said:

In Java 9, the Map interface introduced convenience factory methods to create immutable maps easily. These are:

1. [Link]() – for up to 10 key-value pairs.


Example:
2. Map<String, Integer> map = [Link]("k1", 1, "k2", 2, "k3", 3);
3. [Link]() – for more than 10 entries or when using [Link]().
Example:
4. Map<String, Integer> map = [Link](
5. [Link]("k1", 1),
6. [Link]("k2", 2),
7. [Link]("k3", 3)
8. );

Looking at your options:

• static Map of(K1, V1, K2, V2, K3, V3) → This is [Link]()
• Map of([Link]<K1,V1>, [Link]<K2,V2>, [Link]<K3,V3>) → This is [Link]()

Answer:
Both Option 1 and 2

You said:

Which of the following methods cannot be overridden in a JSP page? Get parameter Jsplit Jspdestroy None

ChatGPT said:

In JSP, there are certain lifecycle methods defined in the HttpJspBase class (which JSP pages extend behind the scenes).
Key points:

• jspInit() – called when the JSP is initialized; can be overridden.


• _jspService() – handles requests; cannot be overridden in JSP page.
• jspDestroy() – called when JSP is destroyed; can be overridden.

Looking at your options:

• Get parameter → Not a JSP lifecycle method.


• Jsplit → Likely a typo; no such method.
• Jspdestroy → jspDestroy() can be overridden.
• None → This would imply all can be overridden.

The correct understanding is: _jspService() cannot be overridden in a JSP page, but it’s not explicitly listed here. Based on
your options, “None” seems to be the intended answer (since the listed options are either not valid methods or
overridable).

Answer: None

You said:

Which of the following connection pools is best for Hibernate? T4d0 T3d0 P3c0 C3p0

ChatGPT said:

For Hibernate, among the options given:

• T4C → Oracle JDBC thin driver pool (not commonly used for general Hibernate apps)
• T3C → WebLogic-specific pool (not general-purpose)
• P3C0 → Likely a typo for Proxool (less commonly used nowadays)
• C3P0 → Widely used, stable connection pool with Hibernate support
Hibernate has built-in support for C3P0, and it’s considered one of the best general-purpose connection pools for
Hibernate.

Answer: C3P0

You said:

Which of the following is not supported by OOPS in term of classes? Multilevel inheritance Multiple inheritance Function
overloaded Function overridden

ChatGPT said:

In OOPS (Object-Oriented Programming):

• Multilevel inheritance → Supported (A → B → C)


• Multiple inheritance → Not supported in Java for classes (a class cannot extend multiple classes; can be
achieved via interfaces)
• Function overloading → Supported (same method name, different parameters)
• Function overriding → Supported (subclass provides specific implementation of superclass method)

Answer: Multiple inheritance

You said:

Consider an instance of a collection of type List<CharSequence> Options The collection can contain a String types
Thecllection can contain only CharSequence types Thes collection can contain both String and CharSequence types The
collection can contain any Object.

ChatGPT said:

We are dealing with List<CharSequence> in Java. Key points:

• CharSequence is an interface implemented by classes like String, StringBuilder, StringBuffer, etc.


• A generic list of CharSequence can hold any object that is a CharSequence or a subclass/implementing class.

Analyzing the options:

1. The collection can contain String types → Correct, because String implements CharSequence.
2. The collection can contain only CharSequence types → Also correct, because everything in the list must
implement CharSequence.
3. The collection can contain both String and CharSequence types → Misleading; String is a CharSequence, so
this phrasing is redundant.
4. The collection can contain any Object → Incorrect; only objects implementing CharSequence are allowed.

The most accurate answer:

The collection can contain String types

It’s correct and specific to the scenario.

If you want, I can explain why List<CharSequence> cannot hold arbitrary objects in detail.

You said:

I want only one answer


ConcurrentHashMap uses object level lock for synchronizing access by multiple thread.... true or false

ChatGPT said:

False

Reason:
ConcurrentHashMap in Java does not use object-level locking. Instead, it uses segment-level or finer-grained locking
(bucket-level in Java 8+ with CAS operations) to allow concurrent access by multiple threads without blocking the entire
map.

This is why ConcurrentHashMap is more efficient than Hashtable or synchronized HashMap.

Answer: False

You said:

In java 8, which of the following JavaScript engine was replaced with Nashorn? V8 Inscript Rhino Narcicious

ChatGPT said:

In Java 8, the JavaScript engine Rhino was replaced with Nashorn.

• V8 → Google’s JS engine for Chrome


• Inscript → Not a valid JS engine
• Rhino → Replaced by Nashorn in Java 8
• Narcicious → Not a valid JS engine

Answer: Rhino

You said:

What are the two types of Streams offered by Java 8? Parallel and Random Sequential and Random Sequential and Parallel
Random and Synchronized

ChatGPT said:

In Java 8, the two types of streams are:

• Sequential Stream → processes elements one by one in order.


• Parallel Stream → processes elements concurrently using multiple threads.

Other options like Random or Synchronized are not types of streams.

Answer: Sequential and Parallel

You said:

Lamda expressions can be serialized, if The captured argumens are serializable ts target type is serializable Only if both its
captured argument and its target type are serializable Serializabilit of arguments and target type does not matter

ChatGPT said:

In Java, lambda expressions can be serialized only if both:


1. The captured arguments (variables from the enclosing scope used inside the lambda) are serializable.
2. The target type (the functional interface the lambda implements) is serializable.

Answer: Only if both its captured argument and its target type are serializable

You said:

The running time of a TreeSet is proportional to which of the following? (where n is the number of elements) Log n N²2 N
N²3

ChatGPT said:

A TreeSet in Java is implemented using a Red-Black Tree, which is a self-balancing binary search tree.

• Basic operations like add(), remove(), and contains() have a running time of O(log n), where n is the number of
elements.

Answer: Log n

You said:

As per ElB concepts, which of the following statements about JNDI (Java Naming and Directory Interface) is true? INDI is a
directory service like LDAP or Netscape Directory Server. OINDI is a service only provided by EJB container and used for
EJB's look up. JNDI offers location transparency. JNDI can be used to read java objects but not write back from directories

ChatGPT said:

The correct statement about JNDI (Java Naming and Directory Interface) is:

JNDI offers location transparency.

Explanation:

• JNDI is an API that allows Java applications to look up objects (like EJBs, datasources, environment entries) in a
naming/directory service.
• It does not itself provide a directory service, but can interface with services like LDAP.
• It allows clients to access resources without knowing their physical location, hence location transparency.
• JNDI can be used for both read and write operations depending on the underlying directory, so the last option is
incorrect.

Answer: JNDI offers location transparency

You said:

How would you check the condition of the current transaction in a bean-managed transaction? By performing a INDI
lookup for "java:comp/TransactionStatus" getStatus) on the [Link] reference getStatus() on the EJBContext
reference getStatus() on the User Transaction reference

ChatGPT said:

In EJB with Bean-Managed Transactions (BMT), the transaction is controlled by the bean itself using the UserTransaction
interface.

To check the status of the current transaction, you use:

@Resource
private UserTransaction userTransaction;

int status = [Link]();

• [Link]() returns the current transaction status.


• [Link]() only checks rollback state, not full status.
• JNDI lookup "java:comp/TransactionStatus" or [Link]() are incorrect.

Answer: getStatus() on the UserTransaction reference

You said:

What should be done for an interface to act as a remote interface? Alt must extend [Link] [Link] method must
declare [Link]. RemoteException

ChatGPT said:

For an interface to act as a remote interface in Java RMI:

1. The interface must extend [Link]


2. Each method must declare [Link] in its throws clause

Both conditions are mandatory for RMI remote interfaces.

Answer: Both A and B

You said:

Answer the below question based on ISP concepts What is the difference between HttpServletResponse redirect method
and RequestDispatcher's forward method? RequestDispatcher Forward a request from a servlet to another resource on the
server. HttpServletResponse redirect temporary redirect response to the client using the specified redirect location URL.
RequestDispatcher forward method temporarily redirect response to the client using the specified redirect location URI.
HttpServletResponse redirect a request from the servlet to another resource on the server. RequestDispatcher forward can
forward the request to outside the container for example [Link] None of these

ChatGPT said:

The correct distinction based on Servlet API behavior is:

• [Link]() → Forwards a request from a servlet to another resource on the server. The client
does not see the URL change.
• [Link]() → Sends a temporary redirect response to the client, instructing it to
request a new URL, which can be inside or outside the server.

Answer:
RequestDispatcher Forward a request from a servlet to another resource on the server. HttpServletResponse redirect
temporary redirect response to the client using the specified redirect location URL.

You said:

Following are benefits of using Stream API: ability to write in Functional Style programming perform Parallel and Pipelining
operations ability to achieve better performance All of above A and B

ChatGPT said:
The Stream API in Java 8 provides:

• Ability to write in functional style → Using lambda expressions and method references
• Perform parallel and pipelined operations → Streams can be sequential or parallel
• Ability to achieve better performance → Parallel streams can improve performance on multi-core systems

Answer: All of above

You said:

Inheritance is used in decorator pattern to achieve type matching of decorator classes with ConcreteComponent class.
What would you do to get the behavior of decorator classes? Inheritance Aggregation O Composition Generalization

ChatGPT said:

In the Decorator Pattern, to add behavior dynamically to objects without modifying their class:

• Inheritance is used for type matching with the component interface or class.
• Composition (or aggregation) is used inside the decorator to hold a reference to the component and delegate
calls.

The question asks specifically: “to get the behavior of decorator classes”, which refers to wrapping a component inside
the decorator.

Answer: Composition

You said:

Which of the following statements about MVC is true? MVC decouples views and models using a subscriber/notify protocol
i.e. the Observer pattem Views are generally nested using a factory design pattern. The controller in MVC are generally
heavy since they are responsible for controlling the operations of the Views and models. MVC was a framework invented in
1980s and was used in legacy systems and is no longer relevant for mobile and web applications.

ChatGPT said:

The correct statement about MVC (Model-View-Controller) is:

MVC decouples views and models using a subscriber/notify protocol i.e. the Observer pattern

Explanation:

• MVC separates Model, View, and Controller.


• Model notifies Views of changes (Observer pattern), keeping them decoupled.
• Views are not necessarily nested using a factory; that’s unrelated.
• Controllers are ideally thin, not heavy, in modern MVC design.
• MVC is still widely relevant for web and mobile applications.

Answer: MVC decouples views and models using a subscriber/notify protocol i.e. the Observer pattern

You said:

As per design patterns concepts, which of the following options is an object, representing another object, That provides a
surrogate or placeholder for another object to control access to it? Singleton Proxy Ioc None

ChatGPT said:
The design pattern that provides a surrogate or placeholder for another object to control access is:

Proxy

Explanation:

• Proxy Pattern → An object (proxy) controls access to another object (real subject).
• Singleton → Ensures only one instance exists.
• IoC (Inversion of Control) → Refers to dependency management, not a structural pattern.

Answer: Proxy

You said:

As per design patterns concepts, which of the following statements is true? An Abstract Factory pattern usually has
multiple factory implementations. In Abstract Factory pattern, generally a key or a parameter is provided and the metho
obtains an object of that type. The Singleton design pattern is a creational type of design pattern which does not assure to
have only a single instance of a class. All of the given options

ChatGPT said:

The correct statement based on design patterns concepts is:

An Abstract Factory pattern usually has multiple factory implementations.

Explanation:

• Abstract Factory → Provides an interface for creating families of related or dependent objects without specifying
their concrete classes. Usually, multiple concrete factories implement this interface.
• The second statement describes the Factory Method pattern, not Abstract Factory.
• Singleton does ensure a single instance, so the third statement is false.

Answer: An Abstract Factory pattern usually has multiple factory implementations.

You said:

Answer the following based on your knowledge of Java Programming-Spring. Which of the following annotation is provided
to load a spring container in application Junit test? Component Configuration ContextConfiguration Configurable

ChatGPT said:

In Spring JUnit tests, to load the Spring container, you use:

@ContextConfiguration

Explanation:

• @ContextConfiguration → Specifies the configuration classes or XML files to load the Spring application context
for tests.
• @Component → Marks a class as a Spring bean.
• @Configuration → Marks a class as a source of bean definitions.
• @Configurable → Allows dependency injection into non-Spring-managed objects.

Answer: ContextConfiguration

You said:
Which of the following statements is FALSE regarding bean naming? A bean may be defined without an id or a name. ☐ It
is possible for a bean to have multiple names. The following declarations are both legal: <bean id="/myBean"
class="[Link]"/> OR <bean name="/myBean" class="[Link]" /> A bean may be given multiple names via the tag

ChatGPT said:

The FALSE statement regarding Spring bean naming is:

“A bean may be given multiple names via the tag”

Explanation:

• A bean can be defined without an id or name → True, Spring will generate a default name.
• A bean can have multiple names → True, using name="name1,name2" (comma or space separated).
• Both <bean id="myBean" ...> and <bean name="myBean" ...> are legal → True.
• “A bean may be given multiple names via the tag” → False as phrased, because you cannot define multiple
<bean> tags for the same bean to give it multiple names; multiple names are assigned via the name attribute,
not by multiple tags.

Answer: A bean may be given multiple names via the tag

You said:

What are Spring aspects implemented as? Direct methods Proxies that wrap the methods They are auto implemented
None of the above

ChatGPT said:

In Spring AOP, aspects are implemented as:

Proxies that wrap the methods

Explanation:

• Spring uses proxy-based AOP (either JDK dynamic proxies or CGLIB proxies) to weave aspects into beans.
• The proxy wraps the target method and executes advice (before, after, around) at runtime.
• Aspects are not direct methods and are not automatically injected without proxying.

Answer: Proxies that wrap the methods

You said:

Which of the following is not supported in Spring MVC? idbcDaoSupport HibernateDaoSupport JdoDaoSupport
JavaDaoSupport

ChatGPT said:

The option that is not supported in Spring MVC is:

JavaDaoSupport

Explanation:

• JdbcDaoSupport → Supported, provides JDBC support.


• HibernateDaoSupport → Supported, provides Hibernate support.
• JdoDaoSupport → Supported, provides JDO support.
• JavaDaoSupport → Not a valid Spring class; does not exist in Spring.

Answer: JavaDaoSupport

You said:

Choose the correct option. Which of the following Hibernate objects is synchronized with database at the end of
transaction? transient Odetached persistent none of the above

ChatGPT said:

In Hibernate, the object state determines its interaction with the database:

• Transient → Not associated with a session; not saved to DB.


• Detached → Was associated with a session but currently not synchronized.
• Persistent → Associated with a session; automatically synchronized with the database at the end of the
transaction.

Answer: persistent

You said:

How can an entire class be mapped as immutable? By using the mutable="false" attribute in the class mapping. By using
the ismutable="false" attribute in the class mapping. By using the ismutable="no" attribute in the class mapping. None of
the above

ChatGPT said:

In Hibernate, to map an entire class as immutable, you use the attribute:

mutable="false" in the class mapping.

Explanation:

• mutable="false" → Hibernate treats the entity as read-only; any changes to instances will not be updated in the
database.
• ismutable or ismutable="no" are incorrect.

Answer: By using the mutable="false" attribute in the class mapping.

You said:

Answer the following questions based on your knowledge of Hibernate. Which of the following is false about a session in
hibemate? Session is a light weight object It represents a single unit of work with the database Session can be shared
between threads None of the above

ChatGPT said:

The FALSE statement about a Hibernate Session is:

Session can be shared between threads

Explanation:

• Session is lightweight → True


• Session represents a single unit of work → True
• Session is not thread-safe → Cannot be shared between threads; each thread should use its own session.

Answer: Session can be shared between threads

You said:

Consider the following statements: S1- When Hibernate places an object in the database, it must be sure that each row is
unique, because the rows represent specific objects. S2- It is possible for two objects in the system to have the same
attribute values. S3- If this occurs, the system needs to be able to distinguish the objects in the database. Which of the
above statements is correct?

ChatGPT said:

All three statements about Hibernate and object identity are correct:

• S1: Hibernate needs each row to be unique because each row represents a specific object.
• S2: Two objects in the system can have the same attribute values.
• S3: Even if attribute values are identical, Hibernate distinguishes objects using the primary key (identifier) in
the database.

Answer: S1, S2, and S3 are correct

You said:

Which of the following is not introduced in Java 9? Multirelease JAR Private Methods in Interfaces Lambda expressions
HTML5 based java documentation

ChatGPT said:

The feature not introduced in Java 9 is:

Lambda expressions

Explanation:

• Multirelease JAR → Introduced in Java 9


• Private methods in interfaces → Introduced in Java 9
• Lambda expressions → Introduced in Java 8, not Java 9
• HTML5-based Java documentation → Introduced in Java 9

Answer: Lambda expressions

You said:

Which of the following correctly describes the defaultExecutor() method of CompletableFuture Interface? This method
completes this CompletableFuture with the given value if not otherwise completed before the given timeout. This method
exceptionally completes this CompletableFuture with a TimeoutException if not otherwise completed before the given
timeout. Returns a new incomplete CompletableFuture of the type to be returned by a Completion Stage method. None

ChatGPT said:

The correct description of defaultExecutor() in the CompletableFuture interface is:

None
Explanation:

• defaultExecutor() returns the default Executor used by asynchronous methods like supplyAsync() or runAsync()
when no explicit executor is provided.
• The options listed describe complete(), completeExceptionally(), or factory methods, not defaultExecutor().

Answer: None

You said:

What would happen if we directly call run method of thread? class Multi extends Thread( public void run()(
[Link]("running"); public static void main(String args[]){ Multi 11-new Multi(); [Link](); } }

ChatGPT said:

If you directly call the run() method of a Thread object instead of start(), the thread does not run in a separate new
thread. Instead, the run() method executes in the current thread just like a normal method call.

For your code:

class Multi extends Thread {

public void run() {

[Link]("running");

public static void main(String args[]) {

Multi t1 = new Multi();

[Link](); // Direct call

Behavior:

• Output:

running

• Threading: No new thread is created; main thread executes run().

Key point: To actually start a new thread, you must call [Link](), not [Link]().
JAVA 9 MOCK TEST
[Link] Copyright © [Link]

Advertisements

This section presents you various set of Mock Tests related to Java 9. You can download these sample
mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a
mock test key to let you verify the final score and grade yourself.

JAVA 9 MOCK TEST

Q 1 - Which of the following method is added to Set in Java 9?

A - static Set of(E e1, E e2, E e3)

B - Set ofSet(E e1, E e2, E e3)

C - Both of the above.

D - None of the above.

Q 2 - Which of the following method is added to Map in Java 9?

A - static Map of(K k1, V v1, K k2, V v2, K k3, V v3)

B - Map ofMap(K k1, V v1, K k2, V v2, K k3, V v3)

C - Both of the above.

D - None of the above.

Q 3 - Which of the following method is added to Map in Java 9?

A - static Map ofEntries([Link]<? extends K,? extends V>... entries)

B - Map ofMapEntries(K k1, V v1, K k2, V v2, K k3, V v3)

C - Both of the above.


D - None of the above.

Q 4 - Which of the following method is correct about List in Java 9?

A - For List interfaces, of(...) method is overloaded to have 0 to 10 parameters.

B - For List interfaces, of(...) method is overloaded to have var arg as parameter.

C - Both of the above.

D - None of the above.

Q 5 - Which of the following method is correct about Set in Java 9?

A - For Set interfaces, of(...) method is overloaded to have 0 to 10 parameters.

B - For Set interfaces, of(...) method is overloaded to have var arg as parameter.

C - Both of the above.

D - None of the above.

Q 6 - Which of the following method is correct about Map in Java 9?

A - For Map interfaces, of(...) method is overloaded to have 0 to 10 parameters.

B - For Map interfaces, ofEntries(...) method is having var arg as parameter.

C - Both of the above.

D - None of the above.

Q 7 - Which of the following is a not valid member of interface till Java 7?

A - Constant variable

B - Abstract method

C - Default method.

D - All of the above.

Q 8 - Which of the following is a not valid member of interface till Java 7?

A - Constant variable

B - Abstract method

C - Static method.

D - All of the above.


Q 9 - Which of the following is a not valid member of interface till Java 8?

A - Private method

B - Default method

C - Static method.

D - All of the above.

Q 10 - Which of the following is a not valid member of interface till Java 8?

A - Private static method

B - Default method

C - Static method

D - All of the above.

Q 11 - Which of the following is a not valid member of interface till Java 8?

A - Private static methods

B - Default method

C - Static methods

D - All of the above.

Q 12 - Which of the following is a valid member of interface in Java 9?

A - Private static methods

B - private methods

C - Both of the above

D - None of the above

ANSWER SHEET

Question Number Answer Key

1 A

2 A

3 A
4 C

5 C

6 C

7 C

8 C

9 A

10 A

11 A

12 C

You might also like