Java Mycompetency Final
Java Mycompetency Final
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.)
Java
//CODE TO ESTABLISH CONNECTION (from page 25)
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:
Question 1
What will be the outcome when the given code is compiled and run?
class Test27 {
Options:
1. true
1. compilation error
1. false
1. NaN
Question 2
MyThread() {}
MyThread(Runnable r) {
super(r);
} class Test {
new MyThread().start();
Options:
1. Prints "Inside Thread Inside Thread"
1. Compilation Fails
1. Runtime Exception
Question 3
Options:
1. Thread will not come alive again but the program will not throw any exception
Question 4
Options:
1. GET
1. POST
1. HEAD
1. PUT
Question 5
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
Options:
1. Object
1. Class
Question 7
Options:
Question 8
Options:
1. ListResultSet
1. ResultSet
1. ScrollableResultSet
1. ScrollableResult
Question 9
Thread t = [Link]();
[Link](t);
Options:
1. Runtime error
1. Thread[main,5,main]
1. Thread[main,5]
Question 10
Options:
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()?
[Link]("running");
Options:
1. Runtime error
Question 12
try {
return;
} catch(Exception e) {
[Link]("catch");
} finally {
[Link]("finally");
Options:
1. catch
1. finally
1. nothing
Question 13
1. None
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)
Question 15
try {
return;
} catch(Exception e) {
[Link]("catch");
} finally {
[Link]("finally");
Options:
1. catch
1. finally
1. nothing
1. compile time error
Question 16
Options:
1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue.
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
Options:
1. put()
1. head()
1. delete()
1. resume()
Question 18
class q33 {
Object obj = f;
[Link](f[0]);
Options:
1. Compilation Error
1. Runtime Exception
1. 0.0
1. 0
Question 19
Which one of the following could be closest to the key reason for including lambda expressions in JDK 8?
Options:
1. Make the Java programming language look more like a functional programming language
Question 20
[Link] r = () -> {
};
Options:
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
try {
int i = 5 / 0;
} catch(Exception e) {
[Link]("In Finally");
Options:
1. Compilation Fails
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
Options:
Question 23
Options:
1. None
Question 24
What is the use of abstract-schema-name entry in a CMP 2.0 entity bean's deployment descriptor?
Options:
1. It specifies the table in the database that will contain the persistent state
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
Options:
1. jspInit()
1. jspLoad()
1. jspGet()
1. jspPost()
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)
Question 27
Options:
1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue
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
Options:
1. put()
1. head()
1. delete()
1. resume()
Question 29
class q33 {
Object obj = f;
[Link](f[0]);
Options:
1. Compilation Error
1. Runtime Exception
1. 0.0
1. 0
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>
</transportConnectors>
<transportConnectors>
</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
Question 32
Which of the following object is used to access web services via browsers?
Options:
1. XmlHttpRequest
1. SmlHttpRequest
1. JSONP
1. WebSocket
Question 33
class Test {
Thread t = [Link]();
[Link](t);
class Test { public static void main(String args[]) { Thread t = [Link](); [Link](t); } }
Options:
1. Runtime error
1. Thread[main,5,main]
1. Thread[main,5]
Question 34
import [Link];
import [Link];
import [Link];
class Test {
[Link](null, 1);
[Link](3, 2);
Set s = [Link]();
while([Link]()) {
[Link]([Link]());
Options:
1. 3
1. null 3
1. [Link] at runtime
1. null
Question 35
try {
return;
} catch(Exception e) {
[Link]("catch");
} finally {
[Link]("finally");
Options:
1. catch
1. finally
1. nothing
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)
Question 37
Options:
1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue
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
Options:
1. put()
1. head()
1. delete()
1. resume()
Question 39
Object obj = f;
[Link](f[0]);
Options:
1. Compilation Error
1. Runtime Exception
1. 0.0
1. 0
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>
</transportConnectors>
<transportConnectors>
</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
try {
return;
} catch(Exception e) {
[Link]("catch");
} finally {
[Link]("finally");
Options:
1. catch
1. finally
1. nothing
Question 42
Options:
1. jspInit()
1. jspLoad()
1. jspGet()
1. jspPost()
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)
Question 44
Options:
1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue
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
Options:
1. put()
1. head()
1. delete()
1. resume()
Question 46
class q33 {
Object obj = f;
[Link](f[0]);
Options:
1. Compilation Error
1. Runtime Exception
1. 0.0
1. 0
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>
</transportConnectors>
<transportConnectors>
</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
Options:
Question 49
Options:
1. Object
1. Class
Question 50
Which one of the following could be closest to the key reason for including lambda expressions in JDK 8?
Options:
1. Make the Java programming language look more like a functional programming language
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
try {
int i = 5 / 0;
} catch(Exception e) {
} finally {
[Link]("In Finally");
Options:
1. Compilation Fails
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
Statement: Lambda Expression is an anonymous function which accepts a set of input parameters and returns results.
Options:
1. TRUE
1. FALSE
Question 53
Options:
Question 54
Options:
1. Object
1. Class
Question 55
void display(int i) { }
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
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
Options:
1. servlet
1. servlet-mapping
1. listener-name
1. listener-class
Question 57
class Test {
try {
int i = 5 / 0;
} catch(Exception e) {
} 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
Options:
1. put()
1. head()
1. delete()
1. resume()
Question 59
Options:
1. XmlHttpRequest
1. SmlHttpRequest
1. JSONP
1. WebSocket
Question 60
Options:
1. The "acknowledge" keyword is used in queries while using JMS like ApacheMessage Queue
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.
Options:
1. To simplify the development of Java enterprise applications by offering a comprehensive programming and
configuration model
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.
Options:
1. AOP Module
1. Core Container
1. Data Access/Integration
1. Spring MVC
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.
1. @Service
1. @Repository
1. @Component
1. @Controller
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.
Options:
1. Inversion of Configuration
1. Inversion of Control
1. Initialization of Components
1. Integration of Code
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.
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
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
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
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
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.
Options:
1. [Link]
1. [Link]
1. [Link]
1. [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.
Options:
1. To manage transactions
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.
Options:
1. @Table
1. @Entity
1. @Persistence
1. @Data
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.
Options:
1. saveObject()
1. persist()
1. save()
1. store()
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.
1. @Primary
1. @Key
1. @Id
1. @PK
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.
Options:
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.
Options:
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.
Options:
1. [Link](Class, id)
1. [Link](Class, id)
1. [Link](Class, id)
1. [Link](Class, id)
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
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).
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.
Options:
1. James Gosling
1. Dennis Ritchie
1. Bjarne Stroustrup
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++.
Options:
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
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.
Options:
1. Object-oriented
1. Use of pointers
1. Portable
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.
Options:
1. .js
1. .txt
1. .class
1. .java
Explanation:
Java source files always use the .java extension; compiled bytecode has the .class extension.
class increment {
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.
Options:
1. final
1. static
1. const
1. immutable
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.
Options:
1. MAVEN_Path
1. JavaPATH
1. JAVA
1. 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.
Options:
1. MemoryError
1. OutOfMemoryError
1. MemoryOutOfBoundsException
1. MemoryFullException
Explanation:
If the JVM cannot allocate more objects due to insufficient heap space, it throws an OutOfMemoryError.
Options:
1. Polymorphism
1. Inheritance
1. Compilation
1. Encapsulation
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?
<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>
Question 2
Options:
1. PropertyPlaceholderConfigurer
1. PropertySourcesPlaceholderConfigurer
1. Multirelease JAR
Question 3
Which Hibernate object is synchronized with the database at the end of a transaction?
Options:
1. transient
1. detached
1. persistent
Question 4
Which of the following HQL statements returns all persistent objects of a Hibernate application?
Options:
Question 5
Options:
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
Question 7
Options:
1. Concerns
1. Objects
1. Hierarchical Objects
Question 8
Options:
1. CGLIB proxies
Question 9
Which annotation is used to load a Spring container in a JUnit test?
Options:
1. @ContextConfiguration
1. @SpringBootTest
1. @RunWith([Link])
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
Question 11
In Spring Framework's declarative transaction implementation, is it sufficient to annotate classes with @Transactional?
Options:
1. Yes
1. No
Question 12
Options:
1. @Component
1. @Service
1. @Repository
1. @Controller
1. @ExceptionHandler
Question 13
Options:
1. @ContextConfiguration
1. @SpringBootTest
1. @RunWith([Link])
Question 14
Options:
1. Reading data
1. Writing data
Question 15
Options:
1. Adapter
1. Proxy
1. Iterator
1. Prototype
Question 16
Options:
1. Both A and C
Question 17
Options:
1. A and B
Question 18
Options:
1. Lambda Expressions
1. Default Methods
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. 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
Question 21
Options:
1. Bean-managed persistence
1. Container-managed persistence
Question 22
Options:
1. PrimaryKey class
Question 23
Options:
1. sendRedirect() sends a new request; forward() forwards within the same request
Question 24
Options:
1. PropertyPlaceholderConfigurer
1. PropertySourcesPlaceholderConfigurer
1. PropertyOverrideConfigurer
Question 25
The Queue interface represents which data structure?
Options:
1. LIFO
1. FIFO
1. Both
1. None
Question 26
Options:
1. Stream API
1. Spliterator
1. Removal of PermGen
1. Serialization
1. Lambda Expression
Question 27
Options:
1. Stream API
1. Lambda Expression
1. Default Methods
Question 28
Options:
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?
<transportConnectors>
</transportConnectors>
Question 30
Options:
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
1. Hash Table
1. Red Black Tree (marked)
1. Array
Q2
ConcurrentHashMap uses object level lock for synchronizing access by multiple threads.
1. TRUE (marked)
1. FALSE
Q3
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
Q5
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
1. TRUE
1. FALSE (marked)
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 );)
Q8
1. V8
1. Inscript
1. Narcissus
1. Rhino (marked)
Q9
Q10
Q11
Consider lambda expression name -> [Link](name) when passed to [Link](); which is correct?
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 finally
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
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
Q18
1. Virtual polymorphism
1. Transient polymorphism
1. Pseudo polymorphism
Q19
Java Stream API can be used for applying Map-Reduce kind of transformations on collections.
1. true (marked)
1. false
Q20
Which structural design pattern uses shared objects in multiple contexts to minimize memory?
1. Flyweight (marked)
1. Singleton
1. Prototype
1. None
Q21
Q22
1. [Link] (marked)
1. Infinity
1. 0
Q23
1. Thread will not come alive again but program will not throw exception
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
1. Function Overloading
1. Abstract Classes
1. Operator Overloading
1. Virtual Functions
Q26
1. ConcurrentMap
1. HashMap (marked)
1. ArrayList
1. SortedMap
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
1. Adapter
1. Proxy
1. Iterator (marked)
1. Prototype
Which pattern separates object construction from representation so same construction can create different
representations?
1. Prototype
1. Builder (marked)
1. Both
1. None
Q30
Q31
Which pattern creates instances of families of related objects without specifying concrete classes?
1. Factory
1. Adapter
1. None
Q32
1. public
1. static
1. private (marked)
1. final
Q33
What is JVM?
1. Bootstrap
1. Interpreter
1. Extension
1. Compiler (marked)
Q34
1. JVM (marked)
1. JDK
1. JIT
1. JRE
Q35
Q36
Based on which jar file in JDK 1.7 do JCL classes run?
1. [Link] (marked)
1. [Link]
1. [Link]
1. sa-jdl
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. Runtime exception
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
1. Color
1. Component
1. Cursor
1. Stroke (marked)
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
Q43
Q44
What does this code print? boolean testB = false; if (testB = true) [Link]("TRUE"); else
[Link]("FALSE");
1. FALSE
1. TRUE (marked)
1. None
1. true
1. false (marked)
Q46
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
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
1. Both 1 and 2
1. None
Q49
Q50
1. None
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
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.
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
Q6 — Serializable inheritance
What is the output of: float f[] = new float[5]; Object obj = f; [Link](f[0]);
Options: Compilation Error / Runtime Exception / 0.0 / 0
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.
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.
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.
Which Spring interface provides mechanism to register objects created outside container?
Options: DefaultListableBeanFactory / AutowireCapableBeanFactory / SimpleBeanFactory / StaticBeanFactory
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.
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.)
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.
Options: JNDI is a directory like LDAP / JNDI only provided by EJB container / JNDI offers location transparency / JNDI can
read but not write objects
What should be done? A) must extend [Link] B) Each method must declare RemoteException
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.
Options: functional style / parallel & pipelining / better performance / All / A and B
Q30 — Behavioral pattern allowing loose coupling where one class coordinates others
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)
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.
Correct pattern: annotate the dependency field or constructor with @Autowired and declare it as a bean; e.g.:
Explanation: Use @Autowired on the dependency field (or constructor) and @RequestMapping on the handler method.
S1: rows represent objects and must be unique; S2: two objects can have same attribute values; S3: system must
distinguish them. Which correct?
Q39 — Interface that helps keep Hibernate apps portable across environments
Options: usage may lead to errors / may be incompatible in future / both / none
Options:
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 }
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
Q8
Which of the following is used to achieve runtime polymorphism?
1. Method overriding
1. Method overloading
1. Return type
1. Virtual function
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
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. 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?
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)
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)
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
Q18
What does SAM stand for in context of Functional Interface?
Q19
Select the single most appropriate description of Lambda expression from the following:
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
Q21
What are the two types of Streams offered by Java 8?
Q22
How can the Advanced Encryption Standard (AES) be disabled using the Java VM Option?
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
Q25
Which of the following statements about stubs and skeletons is true?
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?
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. None of these
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
Q31
Which of the following is not a valid method declaration within an interface in Java?
1. String show();
Q32
Which of the following connection pools is best for Hibernate?
1. c3p0
1. proxool
1. DBCP
1. HikariCP
Q33
Which of the following is not introduced in Java 9?
1. MultiRelease JAR
1. Lambda expressions
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
Q35
Which of the following operations is not supported by HQL?
1. Create
1. Insert
1. Select
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?
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. 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. Lambda expressions
Q39
Which of the following data structures is likely to be used by a TreeMap?
1. Hash Table
1. Array
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
Q43
Which of the following is used to delete all messages in a queue? (duplicate Q1 earlier)
Q44
Which of the following is a correct statement about Process API in Java 9?
1. Both 1 and 2
1. None
Q45
Which of the following is not a valid method declaration within an interface in Java?
1. String show();
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]?
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
return "method4";
@ResponseBody
2.@RequestMapping(value="/method4", headers="name=pankaj")
@ResponseBody
return "method4";
@ResponseBody
return "method5";
3.@RequestMapping(value="/method4", headers="name=pankaj")
@ResponseBody
return "method4";
@ResponseBody
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]("tcp://localhost:61616");
[Link]();
[Link]("tcp/localhost:61616");
[Link]();
[Link]("tcp://localhost:61616");
[Link]();
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:
int x = data;
data = x + amt;
Options:
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 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
Code snippet:
@Test
[Link]();
[Link]();
[Link]([Link]());
void printValue() {
[Link]([Link]());
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class Prototype {}
Options:
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
• 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
Question 7
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
Question 8
Options:
Question 9
What does the following JMS application do for the given class TestQueue?
Options:
Question 10
What happens if a remote client invokes a method on an entity bean that has been removed?
Options:
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:
Question 12
What will happen if a remote client invokes a method on an entity bean that has been removed?
Options:
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
Options:
- To issue requests to objects without knowing anything about the request or the receiver
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:
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
- None of these
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:
try {
} catch (JMSException e) {
[Link](e);
class MyListener {
class MyListener {
// no casting
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:
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:
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
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:
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:
Explanation:
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.
---
3.
Q: The field in an interface is implicitly defined as static, public, final, or 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.
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.
10.
A: Java 7.
---
11.
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: C: 3
3. Q13: Which of the following method is added to Map in Java 9?
A: D: None
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
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
14. Q25: As per EJB concepts, which of the following statements about JNDI (Java Naming and Directory Interface) is
[correct]:
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
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?
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?
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
A: D: JavaDaoSupport
25. Q43: Which of the following methods uses RequestMapping with a class?
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?
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:
class qq361 {
m1(null);
[Link]("Object");
[Link]("String");
Explanation:
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:
class Test {
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>]
o thread-name = main
o priority = 5 (default priority)
o thread-group-name = main
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:
[Link]("Start Method");
[Link]("Run method");
[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:
try {
[Link](b, 0, 1000);
catch(IOException e) {
[Link]([Link]());
[Link]();
catch(FileNotFoundException e) {
[Link]("IO Error");
[Link]([Link]());
[Link]();
Analysis:
Correct Answer:
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:
Options:
Int fun(int a)
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:
@Stateless
@Remote
@Local
// do something
// 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:
Correct Answer:
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:
• 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:
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:
• 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:
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:
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.
If you want, I can explain why List<CharSequence> cannot hold arbitrary objects in detail.
You said:
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.
Answer: False
You said:
In java 8, which of the following JavaScript engine was replaced with Nashorn? V8 Inscript Rhino Narcicious
ChatGPT said:
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:
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:
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:
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.
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.
@Resource
private UserTransaction userTransaction;
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:
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:
• [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
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:
MVC decouples views and models using a subscriber/notify protocol i.e. the Observer pattern
Explanation:
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:
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.
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:
@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:
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.
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:
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.
You said:
Which of the following is not supported in Spring MVC? idbcDaoSupport HibernateDaoSupport JdoDaoSupport
JavaDaoSupport
ChatGPT said:
JavaDaoSupport
Explanation:
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:
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:
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.
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:
Explanation:
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.
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:
Lambda expressions
Explanation:
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:
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.
[Link]("running");
Behavior:
• Output:
running
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.
B - For List interfaces, of(...) method is overloaded to have var arg as parameter.
B - For Set interfaces, of(...) method is overloaded to have var arg as parameter.
A - Constant variable
B - Abstract method
C - Default method.
A - Constant variable
B - Abstract method
C - Static method.
A - Private method
B - Default method
C - Static method.
B - Default method
C - Static method
B - Default method
C - Static methods
B - private methods
ANSWER SHEET
1 A
2 A
3 A
4 C
5 C
6 C
7 C
8 C
9 A
10 A
11 A
12 C