CTA
Looking to crack your next Java interview or get a well-paid Java EE developer job? Whether you’re a new graduate, an intermediate Java developer, or a professional backend engineer, having a command of J2EE (Java 2 Platform, Enterprise Edition) concepts can simply contribute to your career success in technical interviews.
In 2025, Recruiters are searching for developers who are proficient in Java technologies at the level that enterprises require at all times in the IT job market. This guide includes a list of top J2EE interview questions with well-detailed, easy-to-read answers with real-world examples and conceptual diagrams.
Whether you are interviewing at TCS, Infosys, Accenture, Wipro, Cognizant, or leading product-oriented firms like Oracle, IBM, or HCL, this handpicked collection of core J2EE interview questions will assist you in cracking your next J2EE interview.
Basic J2EE Interview Questions
These beginner-friendly questions are great for freshers and those preparing for their first Java developer interview.
1. What is J2EE and how does it differ from J2SE?
J2EE (Java 2 Platform, Enterprise Edition) is Java’s development platform for large-scale, enterprise applications. It builds upon Java SE (Standard Edition) and includes APIs and services for multi-tiered, distributed applications. Java SE (J2SE) provides you with the base Java language and standard libraries (collections, I/O, GUI, networking, etc.), whereas Java EE/J2EE provides extra libraries for enterprise use, like web servlets, JSP, EJB, JMS, JPA, JAX-RS, etc.
Basically, J2EE is a superset of J2SE intended for use with server-side, web, and enterprise software. J2EE is a platform based on the Java SE platform. It provides a platform API and runtime environment for developing and deploying large-scale, multi-tiered, easily scalable, reliable, and secure network applications.
2. What are the main components of J2EE architecture?
J2EE utilizes a multi-tier, component-oriented architecture. The most typical tiers are:

- Client level: Web browser or standalone Java clients. This level consists of UI code (JavaScript/HTML) and client logic.
- Web (presentation) level: Includes web components such as Servlets, JSPs, JSF pages, and related helper classes. These are executed by the web container and handle HTTP requests, sessions, and interactions with clients.
- Business (EJB) layer: Contains business logic implemented by EJBs or CDI beans. These are executed by the EJB container, providing services like transactions, security, concurrency, and pooling. The functional core of the application lies within the middle layer.
- Enterprise Information (Data) tier: This includes legacy systems and databases. The J2EE applications use JDBC, JPA, or JCA connectors to access this layer.
All J2EE components run inside a container providing services (transactions, security, pooling, lifecycle management).
3. What is a servlet? Explain its role in J2EE.

Answer: A Servlet is a Java class that runs within a web container (an HTTP server like Tomcat, or the web part within an application server). It is typically handled by the javax.servlet.Servlet interface (by subclassing HttpServlet) and can handle HTTP requests and produce HTTP responses. Servlets are the core Java technology for developing dynamic web pages in J2EE. When a client (browser) sends a request over HTTP, it’s intercepted by a web container, mapped to a matching servlet, processed by it, involving business logic (EJBs, database) to generate a response, and ultimately sends out an HTTP response (typically HTML or JSON).
For example:
Here, a servlet returns a plain HTML response at URL /hello. Internally, one init(), many doGet/doPost requests, and finally a destroy() by the container are executed by the servlet.
4. What is JSP, and how is it different from Servlets?
JSP (JavaServer Pages) is a technology that lets you write dynamic web pages using HTML/XML with embedded Java code and tags. JSPs are eventually compiled into servlets by the container.

The key distinction from servlets relates to how they are written down: JSPs allow for HTML-first development using inline scriptlets, custom tags, or Expression Language, whereas servlets are written in plain Java code explicitly rendering out HTML. This makes page layout more convenient when using JSPs.
To illustrate, in a JSP you would use
Hello, <b><%= request.getParameter(“user”) %></b>!
This mixes HTML with a small Java expression. In a servlet, the equivalent would be:
String user = request.getParameter(“user”);
out.println(“Hello, <b>” + user + “</b>!”);
5. What is a simple use case of EJB (Enterprise JavaBeans)?
EJBs are used to encapsulate business logic within an enterprise app, where you need container-provided services such as concurrency, security, transactions, and remote access. A prime example would be an online order processing bean. For example, in an e-commerce app, you can have a Stateless Session Bean to execute order placement:
This bean’s placeOrder method can be executed in a transaction (so database updates commit/roll back in batch) and can be restricted by role. The EJB container manages instances of this bean, handles concurrent invocations, and handles its lifecycle. Use EJBs, says the Oracle tutorial, when remote access, scalability (clustering), or encapsulation of business logic are necessary in the application.
6. What is the purpose of Java Naming and Directory Interface (JNDI)?
JNDI is Java’s API for looking up named objects within a naming service or directory. In J2EE, its use is to search for and retrieve bound resources and services in the namespace within the app server. Some examples include data sources (JDBC connection pools), JMS destinations, EJB references, and environment entries. All are bound within JNDI. A J2EE app uses JNDI to resolve them at runtime.
For instance, a servlet can
DataSource ds = (DataSource)new InitialContext().lookup("java:comp/env/jdbc/MyDB");
Connection conn = ds.getConnection();
The container binds the DataSource object into JNDI at jdbc/MyDB, and app code accesses it. JNDI truly decouples resource config from code. You configure your resource (e.g., database URL) within the server, specify a JNDI name, and your app simply uses it by name, without having any hardcoded data.
7. What is JDBC, and how is it used in J2EE applications?
JDBC (Java Database Connectivity) is Java’s underlying API for accessing relational databases. It provides classes and interfaces (e.g., Connection, Statement, ResultSet) to execute SQL queries and updates. JDBC would be used by DAOs or persistence components to access the data tier in J2EE. Most J2EE applications would use a JNDI DataSource for connection pooling instead of the direct DriverManager.

For example, inside an EJB or a servlet, you can do:
Here, SQL is run against the database by JDBC. Internally, the J2EE container manages the DataSource (pooling, transactions). Basically, JDBC is how Java accesses a database; J2EE applications use it (frequently referencing ORM frameworks like JPA/Hibernate) to write to and read from data.
8. What is the difference between PATH and CLASSPATH in Java?
PATH and CLASSPATH are both environment variables, although they are utilized for distinct purposes:
- PATH: This is an OS-level variable. It lists directories where your operating system will search for executable programs. The OS verifies directories in your PATH when you execute a command like java or javac. That means, in a sense, the PATH shows where the OS can obtain the Java binaries.
CLASSPATH: This is a Java-specific environment variable or command-line parameter. It shows where a Java Virtual Machine is to look for user classes and libraries (that is, .class files and .jar files). At execution time, when you run a Java program, the JVM uses the CLASSPATH to try to find the classes a program uses. If a required class doesn’t exist in the CLASSPATH, you get a ClassNotFoundException.
9. What is JSF (JavaServer Faces) and how does it help in UI development?
JavaServer Faces (JSF) is a Java EE industry standard web development platform for building component-oriented user interfaces. It follows the Model-View-Controller (MVC) design pattern. With JSF, page developers compose pages using reusable UI component tags (e.g., <h:inputText>, <h:commandButton>, etc.) bound to backing beans (managed beans) with data and action.

The FacesServlet, one front-controller servlet, handles UI component trees, validation, and navigation for JSF.
Major benefits of developing UI using JSF are:
- Reusable components: One can use reusable component libraries (standard ones or ones from frameworks like PrimeFaces) for calendars, tables, etc.
- Built-in event handling: The submission, conversion, and input validation are declaratively handled by JSF.
- Managed beans: JSF uses CDI/EJB for managing beans, so you can directly inject resources into UI beans.
- Templating and navigation: JSF supports view template notions and action result-driven automatic page navigation.
JSF simplifies development by providing a component-based approach to developing UI. It encapsulates HTTP request/response handling and makes it possible for developers to focus more on page design and UI logic.
As an example, a JSF page may declare
<h:form>
<h:inputText value="#{userBean.name}" required="true"/>
<h:commandButton value="Submit" action="#{userBean.save}"/>
</h:form>
userBean is a backing bean with a name property and a save() method. The form would be completed by JSF and call save(). Essentially, JSF enables us to build Java-based Web UIs from reusable components and managed beans with minimal boilerplate HTML/servlet code.
10. What are web components in J2EE? Provide examples.
Web components in J2EE (Java EE) are server-side modules in charge of dealing with web requests. The most significant web components are:
- Servlets: Java classes (usually annotated with @WebServlet) that are implementations of the Servlet interface to process HTTP requests.
- JSP pages/JSF pages: JSP (JavaServer Pages) or Facelets (XHTML), combining HTML and Java/JSP tags to create dynamic page content.
- Filters: Java classes implementing javax.servlet.Filter to filter requests/responses for logging, authentication, etc.
- Listeners: Lifecycle event listeners (such as ServletContextListener) for processing lifecycle events.
These are all executed within a J2EE server’s web container. Some examples are
- A servlet annotated with @WebServlet(“/login”) to handle login form submission
- A JSP page called welcome.jsp showing user information from session beans.
- A JSF page user.xhtml page using <h:form> and a managed bean
- An annotated filter (@WebFilter(“/*”)) logs each incoming request.
11. What is a build file in J2EE (e.g., Ant, Maven)?
A build file is a project-specific build definition that outlines how a J2EE app should be compiled, packaged, and deployed. Apache Ant and Apache Maven are two build utilities that are dependent upon build files in order to execute tasks (compile, test, generate WAR/EAR files, manage dependencies, etc.).
- For Ant, it uses a build file, usually named build.xml, which is XML. The build file is comprised of a series of <target>s and <task>s. A build file for Ant can have compile, war, and ear targets, each containing compiler instructions to compile Java code and produce archives. Running ant -f build.xml executes these targets.
- For Maven, pom.xml serves as a build file. It defines the project’s coordinates (groupId, artifactId, version) and dependencies. It applies a convention-over-configuration philosophy: default directory structure and lifecycle. Maven applies pom.xml in order to compile code, resolve dependencies, run tests, and package app (WAR/EAR) upon the mvn package command execution.
12. What is the advantage of a multi-tier architecture in J2EE?
A multi-tier (layered) strategy in J2EE provides separation of concerns, scalability, and maintainability. By decomposing an application into layers (presentation/web, business, data), you can design, scale, and manage each part independently. For example:
- User interaction (servlets, JSP) is handled by the web tier, business logic (EJBs) by the business tier, and persistence (databases) by the data tier.
- You can scale each layer independently: deploy more web servers or more EJB instances, if you need to.
- Layers enable modularity: modifications to the business logic layer (EJBs) do not require modifications to the code for the web interface, etc.
- It also increases security and reliability as business processing can be isolated within a firewall, with business-level control over transactions.
Typically, multi-tier promotes more business component reuse, and load-balancing can be more effectively managed with loosely coupled layers.
13. What is a WAR, EAR, and JAR files in J2EE packaging?
In J2EE packaging:
- WAR (Web ARchive): A WAR file (.war) packages a web application. It encapsulates web components: servlets (.class files), JSPs, HTML/CSS/JS, and WEB-INF directory (web.xml, classes, libraries). All J2EE web modules are contained in a WAR. For example, myapp.war can contain /WEB-INF/web.xml and include com/example/HelloServlet.class.
- JAR (Java ARchive): A JAR (with a .jar extension) is a general Java archive. JARs are often used in J2EE in EJB modules or utility classes. One EJB module might be a JAR with session bean classes plus an ejb-jar.xml descriptor. Utility classes (regular POJOs, software libraries) are packaged within JARs in the app, too.
- EAR (Enterprise ARchive): A master EAR archive for a full enterprise app can be composed of several modules: one or more WARs, one or more EJB JARs, in addition to a META-INF/application.xml deployment descriptor. An EAR is essentially a ZIP (JAR) holding the entire app. The EAR gets installed by the app server, deploying all modules inside it. For example, myenterprise.ear would hold web.war, business.jar, and META-INF/application.xml.
In a nutshell, a WAR for web modules, a JAR for EJB or shared libs, and an EAR for the entire app.
14. What are the benefits of J2EE over traditional web application development?
J2EE has numerous benefits over ad-hoc or conventional methods of developing Web applications. Some key benefits are:
- Standardization and Portability: J2EE encompasses a standardized platform and APIs (for servlets, EJBs, JMS, etc.). Applications are written to the spec and are portable across any compliant server.
- Built-in services: J2EE containers offer out-of-the-box services like transaction control, security, connection pools, caching, logging, and messaging. It’s not necessary for developers to create these from scratch; the container manages them declaratively. Developing gets faster, and bugs are fewer.
- Scalability and Reliability: Due to its multi-tier component architecture, J2EE applications are inherently scalable. Containers enable load-balancing and clustering.
- Component reuse: Business logic can be encapsulated in EJBs or POJOs and reused across numerous parts within an organization. Layer separation (web, business, data) encourages modularity.
- Security: J2EE uses standardized, customizable security (realms, roles, declarative authentication) embedded with the container, rather than ad-hoc schemes found in traditional applications.
To summarize, J2EE eliminates boilerplate and makes enterprise capabilities (transactions, messaging, etc.) “pluggable” by using containers. This translates to increased productivity along with more sustainable, enterprise-level applications versus creating everything by hand in a non-container setup.
15. What is ORM (Object-Relational Mapping) and how does it relate to J2EE?
ORM (Object-Relational Mapping) is a bridge between object-oriented Java code and relational databases. It maps Java classes (objects) to database tables, allowing developers to code against objects rather than having to write SQL. In J2EE, ORM is realized by the Java Persistence API (JPA) and its implementations (such as Hibernate, EclipseLink).
With ORM, you decorate your entity classes with annotations to define how they map to tables. For instance:
ORM Framework automatically creates SQL in order to SELECT, INSERT, UPDATE, or DELETE these objects.
This is a significant improvement over plain JDBC, since you are not hand-writing SQL statements, nor manual handling of ResultSets. The ORM provider (for example, Hibernate) generates optimized statements and can cache objects.
ORM (via JPA) is a best practice in J2EE for persistence, and it can be used with container-managed transactions. Essentially, database access in J2EE applications becomes more object-oriented and less bug-prone, enhancing developer productivity.
16. What is the difference between JDK, JRE, JVM, and JIT?
These are core terms in the Java ecosystem, and they simply denotes to the different parts of Java’s execution environment:
Component |
Full Form |
Description |
Purpose |
Contains |
JDK |
Java Development Kit |
A complete software development kit for Java |
To develop and compile Java programs |
JRE + compiler (javac), debugger, and other tools |
JRE |
Java Runtime Environment |
Provides the environment to run Java applications |
To run Java applications (not to compile) |
JVM + standard libraries |
JVM |
Java Virtual Machine |
A virtual machine that runs Java bytecode |
To execute compiled Java code (.class files) |
Execution engine, memory management, garbage collector |
JIT |
Just-In-Time Compiler |
Compiles bytecode to native machine code at runtime |
To boost the performance of Java applications |
Part of the JVM |
Generally, we can say that the JDK is the full development kit, which typically contains the JRE (runtime libraries + JVM). The JVM is simply the actual engine that runs Java code. The JIT is a generally the component of the JVM that does on-the-fly compilation of bytecode to native code.
17. What is the difference between session and cookie in J2EE web apps?
A cookie and a session are both means to preserve state within a web application, yet are different in how they work:
- A cookie is a small piece of information requested by a server to be stored by a browser to be returned with each request to the same domain. The server can issue a cookie Set-Cookie: userId=12345; HttpOnly, and the browser returns Cookie: userId=12345 in future requests. Cookies are exposed to the client (unless HttpOnly is specified) with a maximum size limit (~4KB). Cookies can be used for client-side state, such as “remember me” tokens, preferences, or to transport the session ID.
- A session (HttpSession) is a server-side object retaining information particular to a user’s interaction with a web app. When a user accesses the app for the first time, the server establishes a session (e.g., session = request.getSession()) and creates a unique session ID. The browser usually gets this ID in a cookie (generally called JSESSIONID). The actual session attributes (user data, shopping cart, etc.) remain on the server.
Intermediate J2EE Interview Questions
This section covers the kinds of questions you are going to face after 1–3 years of experience, real-world concepts, application flow, and deeper J2EE knowledge.
18. What is the servlet lifecycle and its phases?
A servlet executes through the following lifecycle stages:

- init (Initialization and Loading): At startup or at initial servicing (based upon load-on-startup, if specified), the servlet container (web server) loads a servlet class instance. The container invokes a servlet’s init() method a single time to prepare it for any initialization (such as reserving resources). The servlet can now service requests.
- Request Handling (service / doGet/doPost): The container creates HttpServletRequest and HttpServletResponse objects for each HTTP request to a servlet and calls the service() method of the servlet. HttpServlet’s service() calls doGet(), doPost(), etc., depending upon the request method. The servlet services the request, accesses business logic or data, creates a response, and sends back output to the client. The service step occurs aplenty (once per request) on a single servlet instance, usually simultaneously in multiple threads (unless SingleThreadModel, a deprecated part, is specified by the servlet).
- Destruction (destroy): When the container chooses to dispose of the servlet (during shutdown or reloading the app), it invokes a single call to the destroy() method. In destroy(), the servlet must release any held resources (close database connections, terminate background threads, etc.). The servlet object would then be subject to garbage collection, marking the end of its lifecycle.
So the overall cycle would be: load -> init() -> (service() repeatedly) -> destroy(). The most important points are: init() called once for each servlet instance, and service()/doGet() called once per request.
19. What is the purpose of the web.xml deployment descriptor?
The deployment descriptor for a J2EE web application (WEB-INF/web.xml) is the web.xml file. It serves to declare mappings and configuration for web components. Web.xml in particular declares
- Servlet and filter declarations: You map servlet classes to URL patterns, define init parameters, load-on-startup, etc.
- Filter definitions: List your filters along with your URL patterns or servlet names.
- Security constraints: Specify URL patterns requiring authentication or roles, login screens, etc.
- Init parameters: Parameters for a single object.
- Session configuration: Session timeout settings.
- Error pages: Maps certain exceptions or HTTP status codes to error view pages.
- Welcome files, listeners, etc
Many configurations (such as servlet mappings) can be achieved through annotations (@WebServlet, etc.) in newer Servlet API versions (3.0+), but web.xml remains for global configurations (error pages, security, welcome files) or XML-based config if you would rather use XML.
20. What are filters in J2EE and how are they used?
A Filter in J2EE is a reusable element that can modify requests and responses to a servlet or static assets. A Filter class must implement javax.servlet.Filter while overriding its doFilter() method. A Filter can be applied to certain URL values or servlets (either through web.xml or through @WebFilter annotation).
Where a request matches a filter’s mapping, a container calls the filter ahead of the target servlet. Within doFilter(request, response, chain), a filter can examine/alter the request (e.g., verify authentication, log information), then call chain.doFilter(). Likewise, it can examine/alter the response after a servlet has generated it. Filters are suitable for cross-cutting concerns because
- Authentication/Authorization: Validate if user logged in.
- Logging/monitoring: Log execution time or request parameters.
- Compression/Encryption: Enclose the response to compress output or encrypt.
- Character Encoding: Request/response character encoding.
- Caching, etc.: Include caching headers.
As an example, a filter marked with @WebFilter(“/*”) might log each arriving request URL:
21. What are stateful and stateless session beans?
Stateful and stateless are two forms of session beans in EJB:
- Stateful Session Beans: Stateful beans hold state for a particular client for more than one call. Every stateful bean instance exists for one client (conversational state). A shopping cart bean that retains items while the user adds them would be a stateful one. The state of a client (e.g., contents of a shopping cart) is retained within the bean instance variables. Stateful beans are passivated (serialized to disk) when idle, conserving memory, and are activated at need. Employ stateful beans when you want to keep client-specific data within the server throughout calls.
- Stateless Session Beans: These beans hold no client-specific state between calls. Each request is autonomous, and bean instance variables must not rely on any prior state. The container usually holds a pool of stateless bean instances and directs each client invocation to any free instance (quite potentially a new one even next time). A stateless bean might handle currency conversion or validation services, for instance: it doesn’t have to store any information about the client. Stateless beans are very scalable since instances can be shared across clients.
Generally, a key difference is that a stateful bean’s instance variables represent a distinct client session, whereas a stateless bean is merely a pooled worker without any remembrance of previous interactions.
22. What is Java Message Service (JMS) and how does it support asynchronous communication?
JMS (Java Message Service) defines a Java API for messaging. The JMS API enables components within a distributed application to create, send, receive, and read messages. JMS was designed to provide asynchronous, loosely-coupled communication between components within a J2EE system.
In practice, JMS uses two main models:
- Point-to-Point (Queues): One producer sends a message into a queue. A consumer reads from this queue asynchronously. A single receiver consumes each message.
- Publish/Subscribe (Topics): A message is published to a topic by a publisher. Many subscribers (which are listening) get the message in turn, asynchronously.
JMS can be utilized by a J2EE application in this manner: A bean or servlet sends a message to a queue (asynchronous, without blocking). Another entity, potentially a Message-Driven Bean (MDB), waits on this queue. Upon receiving a message, a call to the MDB’s onMessage() method is made. This makes sender-receiver separation in terms of time.
23. What is Java Persistence API (JPA)? Provide a use case.
The Java Persistence API (JPA) is a Java EE industry standard API for object-relational mapping and data persistence. It offers a collection of annotations and interfaces to map Java objects (entities) to database tables, and database operations in object-oriented form. JPA is typically employed within the business layer in J2EE applications for database access.
An example use case would be if you have an app that manages User entities. With JPA, you would have a User class annotated with @Entity, having fields such as id, name, and email. JPA would manage the SQL:
Here, em.find() and em.persist() are JPA operations. The developer doesn’t write SQL as JPA creates it.
So, JPA streamlines J2EE persistence by handling the ORM layer. You use it in any case where the app has to read/write business entities to a database, e.g., retrieving customer records, storing orders, or querying products.
24. What are the key differences between JTA and JDBC transactions?
The key differences between JTA and JDBC transactions are:
Feature |
JDBC Transactions |
JTA (Java Transaction API) Transactions |
Scope |
Local – limited to a single database connection |
Global – can span across multiple transactional resources (DBs, JMS, etc.) |
Used With |
Directly with java.sql.Connection |
Through UserTransaction, TransactionManager, or container-managed transactions (CMT) |
Commit/Rollback |
Manually invoked using conn.commit() or conn.rollback() |
Managed by the container or explicitly through UserTransaction.commit() / rollback() |
Resource Coordination |
Only one resource (e.g., a single JDBC DataSource) |
Multiple resources (e.g., multiple DataSources, JMS queues) via two-phase commit |
Transactional Model |
Single-phase commit |
Two-phase commit protocol ensures atomicity across all enlisted resources |
Container Support |
Not required; used in standalone or simple apps |
Typically used in J2EE environments (EJBs, Servlets, etc.) with application server support |
Configuration Complexity |
Simple to configure and use |
Requires transaction manager configuration and resource enlistment |
Example Use Case |
Updating records in a single database |
Updating two databases and sending a JMS message in a single transaction |
API Layer |
JDBC API (Connection, Statement, etc.) |
JTA API (javax.transaction.UserTransaction, TransactionManager, etc.) |
Best Suited For |
Simple applications with one database |
Enterprise-level apps requiring distributed transaction coordination |
Performance Overhead |
Lower (due to a single resource) |
Higher (due to coordination overhead and complexity) |
25. What is a backing bean in JSF?
In JavaServer Faces (JSF), a backing bean refers to a managed bean that stores data and event handling logic for a given JSF page. It generally complies with JavaBean conventions (getters/setters for properties) and maps to UI components using Expression Language (EL) within the page.
And in user.xhtml:
<h:form>
Name: <h:inputText value="#{userBean.name}" /><br/>
<h:commandButton value="Submit" action="#{userBean.submit}" />
</h:form>
Here, userBean is a backing bean. It gets automatically instantiated by JSF (because of @Named) and gets populated with data from the form. On button clicking, submit() in the bean gets called.
Backing beans usually include UI component properties to manage validation, events, or navigation. Backing beans are termed so because they back the data model of a page.
26. How are local and remote interfaces used in EJB?
In EJB (Enterprise JavaBeans), a bean can expose two kinds of business interfaces to clients: local and remote:
- Local interface: Annotating @Local (or deploying the no-interface view) indicates this bean would be called by clients within one app or JVM. The calls are optimized by using pass-by-reference semantics and not requiring any network marshalling, and are faster. One EJB can @EJB inject another EJB’s local view directly if they are in the same app.
- Remote interface: Annotated @Remote indicates a bean may be called by clients within other JVMs or machines. Remote calls are made using RMI (whether by default JRMP or RMI-IIOP), so data is serialized across a network. Remote interfaces enable true distribution.
In a practical example, you declare a business interface and tag it with @Local public interface FooLocal {. } and/or @Remote public interface FooRemote {. }, then implement it in your EJB class. Local interfaces provide pass-by-reference sharing of objects, while remote interfaces pass by value by default (serialization).
27. What is JAX-RS, and how does it help in building RESTful web services?
JAX-RS (Java API for RESTful Web Services) is a Java EE standard API for creating RESTful web services. It makes the development of REST endpoints easy by utilizing annotations. Using JAX-RS, a developer would define resource classes and decorate them with @Path, and methods with @GET, @POST, etc. JAX-RS itself would map HTTP requests to Java method invocations.
For example:
This code establishes REST endpoints at /widgets. Invoking GET /widgets/123 triggers getWidget(“123”). JAX-RS handles parsing the URL, invoking the function, and serializing the Widget to JSON (via providers such as Jackson).
It manages details such as URI matching, HTTP method dispatching, @Produces/@Consumes content negotiation, and exception mapping. This enables developers to quickly develop lightweight RESTful services within a Java EE container.
28. What is the difference between a servlet container and an EJB container?
A servlet container, also referred to as a web container, and an EJB container are two components of a Java EE server:
- Servlet (Web) Container: This takes care of web components (Servlets, JSPs, JSF). It manages HTTP requests and responses, the servlet lifecycle, sessions, security constraints, and the servlet API. Examples include standalone servlet containers like Apache Tomcat or Jetty. It gives the environment for executing any web-tier code. The servlet container basically deals with web-specific services (HTTP, cookies, URL mapping, etc.).
- EJB Container: It handles enterprise beans (EJBs) and their services. It offers transaction services, concurrency (thread pool), lifecycle, security, and remote/local interfaces for EJBs. The EJB container enables beans to be called by remote clients, pools bean instances, and manages persistence contexts, transaction demarcation, etc. It executes EJB specifications.
Practically speaking, if you deploy a WAR, it gets handled by the servlet container, whereas if you deploy an EJB JAR, it gets handled by the EJB container. Some lightweight servers (e.g., Tomcat) contain a web container (so can’t execute EJBs) whereas full servers (GlassFish, WildFly, etc.) contain both.
29. What are JavaBeans, and how are they used in J2EE applications?
A JavaBean is a reusable Java class with certain conventions (it must have a no-argument constructor, its properties require getters/setters, etc.). JavaBeans are applied in J2EE as straightforward components for data encapsulation and behavior. They are plain POJOs (Plain Old Java Objects) without any special language requirements, yet are serializable with property accessors.
JavaBeans are frequently utilized within JSP pages through the use of <jsp:useBean> action to hold form data or business data. For instance, you might define a User bean with a getName() and a setName(). <jsp:useBean id=”user” class=”com.example.User” scope=”request” /> within a JSP creates one, whereas <jsp:setProperty name=”user” property=”name” value=”Ayaan”/> sets it to have a name.
You will use JavaBeans in J2EE to hold data (such as a shopping cart bean or a form input bean) and for creating your own JSP tags. The point is that they are plain old components with getters/setters that are easy to incorporate within your JSPs and other systems.
30. How does J2EE support transaction management?
J2EE enables transactions mainly by means of the Java Transaction API (JTA) and container-managed services. There are two models:
- Container-Managed Transactions (CMT): CMT is used by default by Enterprise beans (session beans, MDBs). The EJB container begins and commits transactions automatically around business methods, based on transactional attribute settings. The developer doesn’t explicitly call begin() or commit(). For instance, with the default Required attribute, a transaction is begun by the container upon entering the method and committed upon return. This declarative approach makes coding much simpler because commit/rollback are managed by the container. CMT can be applied to EJBs equally, and can even span more than one resource (the container makes use of JTA to coordinate, for example, database and JMS updates).
- Bean-Managed Transactions (BMT): A bean may even manage its own transactions by invoking javax.transaction.UserTransaction. In this case, a call to UserTransaction.begin(), commit(), or rollback() exists within the bean’s code. BMT is applied when you require precise control over transaction boundaries. The calls are guaranteed by the container to be valid, whereas the bean selects precisely where a transaction begins and where it ends.
Internally, the app server leverages JTA along with the XA protocol to manage transactions between multiple resources.
31. What is the role of annotations like @WebServlet and @WebFilter?
These annotations, like @WebServlet and @WebFilter, were introduced in Servlet 3.0 for streamlining configuration. You can directly use them in your code rather than declaring servlets and filters in web.xml
- @WebServlet: Used in a servlet class to identify it as a servlet and specify its URL pattern(s). For instance, @WebServlet(“/report”) applied to a class instructs the container, “this class is a servlet at the /report URL”. The container automatically creates servlet mapping.
- @WebFilter: Used on a filter class to identify it as a filter and specify where it would be applied to URLs or servlets. For instance, @WebFilter(“/*”) applies to all URLs. The filter would be registered in this case by the container without XML configuration.
These annotations make the configuration more declarative in code. Like entries within web.xml, they perform the same job, but are usually clearer to developers (particularly in small apps).
32. How is Hibernate used in J2EE and how does it differ from JDBC?
Hibernate is a widely used Java ORM framework that uses JPA and builds upon it with more capabilities. Hibernate is implemented in J2EE to execute database operations by using objects rather than JDBC. Hibernate generates SQL for you when you use Hibernate. You work with sessions and entities.
For example, to fetch an object, you would use session.get(Product.class, id), while in JDBC you would use Connection.prepareStatement(“SELECT * .”).executeQuery() and map the ResultSet yourself.

The most significant distinctions between Hibernate (ORM) and JDBC are:
- Abstraction: Hibernate offers object-oriented database access. You work with entity classes and queries within HQL/Criteria instead of SQL. JDBC means executing SQL queries manually while iterating over ResultSets.
- Mapping: Hibernate maps Java types to SQL types automatically through annotations or XML. It can map relationships (one-to-many, etc.) and inheritance mapping. JDBC doesn’t have object mapping; you move data manually from ResultSet to your object.
- Caching: Hibernate can use both first-level (session) and second-level optional caches for performance. JDBC doesn’t support any caching beyond that done by a database.
- Portability: Hibernate can produce dialect-specific SQL for a variety of databases. Using JDBC, you would need to modify SQL per vendor.
33. What are connectors in J2EE? Explain Connector Architecture (JCA).
Connectors in J2EE are the Java EE Connector Architecture (JCA) resource adapters. JCA describes a standardized means by which application servers are able to connect to EIS-like legacy systems, ERP systems, or any other external system (e.g., IBM MQ, SAP, even non-relational data stores). A JCA resource adapter resembles a database driver, but for EIS.

The Connector Architecture (JSR 322) defines contracts to be implemented by these adapters so that the application server can control them. For instance, a resource adaptor would connect to the container’s transactional manager, security, and pooling. You configure a connector to a J2EE app and look up a connector through JNDI in a similar fashion to a DataSource. Behind the scenes, the container makes use of JCA’s contracts whereby connection pooling, transactions (support for XA), and security are managed for this EIS.
In short, the JCA adapter matters because it gives a standardized, transportable means to attach a complex external system to a Java EE environment. Rather than implementing proprietary code for every system, vendors offer a JCA adapter. The server then handles it in much the same fashion as JDBC/JMS resources. This makes it easy for enterprise applications to use, for example, a legacy mainframe system, including container-managed transactions and pooling.
Advanced J2EE Interview Questions
These questions cover complex topics like enterprise patterns, transaction management, and system-level decisions – perfect for senior roles or high-level technical interviews.
34. How would you design a large-scale notification system in J2EE?
Implementation of a large-scale, asynchronous notifications system (e.g. email/SMS/push notifications) for J2EE leverages the platform’s messaging capabilities and scalability:
- Asynchronous Messaging: Leverage JMS for decoupling. For instance, in case the event fires a notification, an EJB or a servlet sends a message to a JMS topic or a queue, depending upon whether notifications are broadcasted or point-to-point. This decouples the producer from the processing of notifications.
- Message-Driven Beans (MDBs): Run MDBs listening on the JMS destination. Each MDB can process a message by sending out the alert (email/SMS). MDBs scale with the thread pool in a container, processing multiple messages simultaneously.
- Stateless or Singleton Beans: The actual sending of notifications (e.g., preparing messages, calling external APIs) can be done within stateless session beans. If shared configuration or initialization tasks are required, a singleton bean can be used to initialize resources.
- Load Balancing and Clustering: Run the application across a cluster of machines. JMS destinations can be JMS providers with clustering capabilities (so multiple MDBs spread across different nodes can share the load). Use a front-end load balancer to route HTTP requests.
- Persistence: For reliability, use persistent notifications (in a database with JPA) or utilize durable JMS topics. This prevents notifications from being lost in case one server crashes.
- Retry and Dead-Letter: Add error handling to retry failing notifications or route failing notifications to a dead-letter queue.
- Scalability: Since the system is decoupled and asynchronous, you can scale out with additional MDB instances or servers during peak load without impacting producers.
A potential architecture: Web/UI or EJB fires an event -> Producer EJB sends a JMS message to a Notification Queue -> MDBs are listening on this queue and notify (maybe by a third-party API) -> Log successes/failures to a database. All components are stateless or clustered, with the exception of the queue being durable. This capitalizes on J2EE strengths in messaging and clustered EJB containers for high-volume notification delivery.
35. How do you analyze performance issues in a J2EE application?
J2EE performance analysis consists of a multitude of steps and utilities:
- Monitoring and Profiling: Utilize profilers (e.g., JProfiler, YourKit, Java VisualVM) to spot slow methods, memory consumption, and hotspots in terms of CPU. Profilers are able to instrument executing code, or scan heaps and thread usage.
- Logging/Monitoring: Instrument the app to record timings of requests. Utilize APM software (New Relic, AppDynamics) or JMX metrics to measure response time and throughput.
- Thread Dumps: In case the app appears to be hanging or sluggish, do thread dumps (jstack) to check for blocked threads (deadlock) or garbage collection. Examine using tools such as FastThread
- GC Logs: Make GC logging (-verbose:gc) active to identify ongoing frequent pauses during garbage collection. Employ GC analysis programs to determine if memory parameters require adjustment.
- Database Profiling: Many performance bottlenecks are in the database. Use SQL query logging or the database performance monitoring environment to identify slow queries or lacking indexes.
- Connection Pooling: Verify whether the DB pool of connections is at full capacity, resulting in waits. Size pools correctly.
- Load Testing: Employ software programs like JMeter to mimic load and determine when response times are compromised.
- Concurrency Problems: Identify contention against synchronized blocks or restricted resources (connection limits, thread pools). Regulate pool sizes if need be.
- Network and IO: Look for I/O slowness (web service, file system calls, etc.) that can be handled with asynchronous processing and/or need to be cached.
36. What are the design goals of J2EE architecture?
The design goals of J2EE architecture include:
- Simplify Enterprise Development: Offer a component model and container services so developers can work on business logic, not plumbing. J2EE seeks to boost productivity by providing standardized services (transactions, security, etc.).
- Portability: They must execute any compliant J2EE server without modification. The portability across vendors is guaranteed by the specification.
- Scalability: Large-scale, multi-tiered applications with a large number of users are supported. The architecture enables clustering, load balancing, and stateless components for horizontal scalability.
- Reliability and Security: Offer a solid runtime for mission-critical applications, with inherent security frameworks (realms, roles) and transactional integrity guaranteed (ACID).
- Standardization: Establish a standard platform and APIs (Servlets, EJB, JMS, JPA, etc.) to prevent vendor lock-in and promote interoperability.
- Component Reusability: Promote the construction of applications from reusable, component-level pieces (EJBs, servlets, JSPs). The component-oriented architecture implies you can combine modules (i.e., employ an EJB in one project as a service in another).
- Integration: Provide integration with legacy systems (through JCA) and web services (JAX-WS, JAX-RS) to enable interoperation in enterprises.
By design, J2EE was meant to host the complete lifecycle of business applications, creation, deployment, and administration, in a standardized, scalable, and portable fashion.
37. What is the purpose of heap dumps? How do you take and analyze them?
A heap dump is a snapshot of Java heap memory at a particular moment. It holds all live objects, classes, fields, and references. Heap dumps are precious for debugging memory issues, including memory leaks or excessive memory usage. Through a heap dump, you can observe which objects are occupying the most memory space, which objects are holding onto other objects, and spot leaks (objects that are expected to be garbage-collected but not yet collected).
To obtain a heap dump, you can
- Set up the JVM to dump upon OutOfMemoryError using the -XX:+HeapDumpOnOutOfMemoryError flag.
- Use jmap -dump:live,format=b,file=heap.hprof <pid> while the JVM is running (on many platforms).
- In some environments, tools like JVisualVM or jcmd GC.heap_dump can trigger a dump programmatically.
After you obtain the .hprof file, use software such as Eclipse Memory Analyzer (MAT) or VisualVM heap analyzer. They can display object histograms, dominator trees, and identify “biggest” objects or suspects for a memory leak. You can, for instance, search for the largest memory users or view retained sets of objects to identify leaks.
38. What is JRMP (Java Remote Method Protocol)?
The wire protocol behind Java RMI (Remote Method Invocation) is known as Java Remote Method Protocol, short-form JRMP. It’s a Java-specific protocol employed when one Java Virtual Machine invokes methods upon a remote Java object within a remote JVM. In other words, JRMP is how arguments, method calls, and return values are serialized and transmitted over a network for plain RMI (as opposed to IIOP).
In J2EE, if you make a remote EJB call (as specified by a @Remote interface), JRMP usually serves as transport (other than when RMI-IIOP is utilized for EJB-IIOP). It accomplishes object serialization and garbage collection across JVMs. In essence, JRMP makes remote EJB calls appear to be local calls to the developer by doing the required TCP/IP communication behind the scenes.
39. What is the difference between JAX-WS and JAX-RS in J2EE?
JAX-WS and JAX-RS are two Java APIs for web services, each targeting a different style:
- JAX-WS: This API provides for SOAP-based (XML/SOAP) web services. It creates and consumes WSDL-described services. JAX-WS uses SOAP envelopes over HTTP (or other transport) by default, with support for WS-* standards (security, transactions, etc.). They pass XML payloads according to a schema. JAX-WS is appropriate for use cases requiring formal contracts with enhanced WS-* capabilities.
- JAX-RS: This API for RESTful web services utilizes HTTP methods (GET, POST, etc.) and resource paths (@Path) to define resources. JAX-RS endpoints would produce/consume JSON or XML and are based upon standard HTTP semantics. No WSDL exists, with a focus upon straightforward, stateless URIs.
To recap, JAX-WS covers SOAP, whereas JAX-RS covers REST. If you are looking for a lightweight, stateless service with JSON over HTTP, use JAX-RS.
40. What is a security realm, and how is it used in J2EE applications?
In J2EE, a security realm establishes a security policy domain within the server. It’s a collection of user identities and credentials (and groups) employed in authentication as well as authorization. For instance, an application server may have a “file realm” or “LDAP realm” where user accounts are specified.
If an application is secured (e.g., using security constraints in web.xml or annotations), the container requests the realm to authenticate the user (verify username/password) and verify whether or not the user is a member of the specified roles/groups. The realm is essentially where users are looked up by the server, authenticated (maybe against a database or directory), and determined to have their role mappings.
You might define a realm called appRealm with a user “ayaan” in a group “managers”. If your app defines a role “admin” referencing group “managers“, then when Ayaan logs in, the realm verifies her password and notices she belongs to “managers” and assigns her “admin” role. The container then grants access to admin-only pages.
41. What is a container-managed transaction and how does it differ from bean-managed?
Within J2EE EJBs, two models of transaction management are found
- Container-Managed Transactions (CMT): The EJB container manages transaction boundaries automatically. This is the default case for enterprise beans. You define transaction attributes (e.g., Required, RequiresNew, etc.) using annotations or XML, and the container performs begin(), commit(), or rollback() calls around each called method. The code for the bean does not demarcate transactions explicitly or call commit. That is, a transaction would start by default before entering a method, and commit after completion.
- Bean-Managed Transactions (BMT): The transaction is controlled explicitly by a bean using the JTA UserTransaction interface. The code invokes userTx.begin(), userTx.commit(), etc. in bean-managed mode. You use this where you require fine-grained control (e.g. multiple transactions within a single method call). BMT must be done with caution, with a need for exception catching and roll back by the bean. CMT is typically suitable for simpler use cases, while more complex ones use BMT.
That is, CMT implies that the container indicates when to begin and close the transaction, while the developer need not write commit code. BMT implies “the bean says when to begin/end the transaction” through JTA calls.
42. Explain the role of the @PreDestroy annotation in managed beans.
The @PreDestroy annotation (of JSR-250) indicates a callback method within a managed bean that the container invokes prior to destruction (removal from scope) of the bean. Its purpose is cleanup. For instance, if a bean had opened a file or had a non-memory resource (such as a JMS connection or a thread in the background), the @PreDestroy method must close out those resources.
This method may be guaranteed to be called when the container plans to garbage-collect a bean (such as when shutting down an application or a session.
Here, cleanup() annotated with @PreDestroy would be called by the container prior to shutting down the bean, allowing a closeout of the DB connection. In short, @PreDestroy serves for deterministic destruction logic in managed beans (EJBs, CDI beans, servlets with @WebListener, etc.)
43. How does Spring compare to J2EE?
Spring is a different framework compared to the traditional Java EE model. J2EE (presently Jakarta EE) is a specification with multiple container-provided services, whereas Spring is a lighter-weight framework/library you integrate into your project. Points to compare
- Dependency Injection (DI): They both use DI, although Spring pioneered straightforward DI using annotations and XML. Java EE (CDI) also offers DI, although Spring configuration (and conventions) are generally more flexible.
- POJO-centric: Spring focuses on Plain Old Java Objects. You can define beans without having to subclass special classes or implement server-specific interfaces. EJB3 became POJO-like also, but in previous J2EE versions, EJBs were bloated. Spring enables you to deploy in any servlet container (Tomcat, etc.) without a full EJB container.
- Non-standard vs Standard: Spring isn’t a standard (although widely used). Java EE is a standard platform by specifications. This implies Java EE applications can (theoretically) be ported to any compliant server. Spring applications are portable, but you are locked to the Spring framework (which isn’t vendor-tested like Java EE).
- Services coverage: Spring provides much of this same functionality (transactions, JPA integration, MVC, security) through its own modules (Spring Data, Spring MVC, Spring Security, etc.). Some people like Spring’s programming model (e.g. @Transactional on any class, Spring Data’s rich query derivation) over traditional EJBs and DAOs.
- Configuration: Spring previously necessitated more initial configuration (JavaConfig/XML) while the current Java EE utilizes annotations. This has been made simpler by Spring Boot through auto-configuration.
- Community and Ecosystem: Spring has a highly active community (Spring Boot, Spring Cloud for microservices, etc.). Java EE has standardized APIs and more emphasis on enterprise stability.
44. What are the different modules of Spring that integrate with J2EE?
Spring is a modular system, and most of its modules integrate with J2EE standard technologies:
- Spring Core/Beans/Context: The core modules for bean lifecycle and DI; they can execute in any Java environment, even J2EE.
- Spring ORM: Integrates with JPA (Hibernate, EclipseLink) and MyBatis. It offers EntityManager injection, JPA/Hibernate support, and transactioning for ORM.
- Spring JDBC: Offers JDBC facilities and makes JdbcTemplate use easy. It can work with a JNDI data source or one declared in Spring.
- Spring JMS: Supports integration with JMS providers, enabling messaging sends/receives with Spring’s JmsTemplate along with MessageListenerContainers (similar to MDBs).
- Spring Web MVC: An MVC alternative to Servlets/JSF. It executes in a servlet container environment using controllers, JSP/Thymeleaf/Velocity views.
- Spring Web Flow: For handling conversational state in web applications (such as long-running wizard flows).
- Spring Security: Works in conjunction with J2EE security; can use container security or use its own authentication/authorization with realms or LDAP.
- Spring Web Services: For SOAP or RESTful services; JAX-WS-style (Spring-WS) and JAX-RS style (with Jackson/Rest
- Spring transaction: A central module abstracting transaction handling (JTA or JDBC) and able to use JTA within a J2EE container.
- Spring Integration: Offers lightweight messaging and integration patterns (like EAI).
- Spring Batch: For batch jobs
- Spring Boot: Although not a module, it configures Spring automatically with embedded servers to simplify J2EE-style app deployment.
- Spring Data: Provides unified data access for JPA, NoSQL, etc.
These modules enable Spring applications to seamlessly integrate with a Java EE environment, taking advantage of JEE resources (DataSources, JMS, JPA) while providing Spring conveniences. A few examples are using Spring MVC for web tiers, Spring ORM for business tiers, and Spring Security for securing J2EE apps.
45. What are the differences between EJB and plain POJOs?
The key distinction is that an EJB (Enterprise JavaBean) is a specially designated POJO, controlled by the EJB container, and thus, it carries additional services, while a plain POJO carries none of those by default. The key distinctions are
- Container Services: EJBs are automatically provided with container services such as transactions, security, concurrency, and pools. A POJO isn’t; you would need to do those yourself.
- Lifecycle: The EJBs have a lifecycle within the container (instantiation, injection, pooling, passivation, etc.). A POJO, however, is a regular Java object without any container callbacks (unless added explicitly).
- Lookup/Injection: EJBs are referenced/deployed through JNDI or @EJB injection. POJOs are new or injected through Spring/CDI.
- Interfaces: EJBs are typically implemented using business interfaces (remote/local). POJOs can also implement interfaces, but a container doesn’t require them to.
- Remoting: Remote EJBs are callable from other JVMs. POJOs are restricted to be called within one JVM (or exposed by something like RMI by hand).
- Annotations/Config: EJBs are annotated using @Stateless, @Stateful, @Singleton, or @MessageDriven. A POJO lacks any such annotation except when you are using frameworks.
46. What happens if the database connection pool goes down during operation?
If a database connection pool fails (e.g., because the database server crashes), any connection retrieval (e.g., dataSource.getConnection()) will result in an exception (such as SQLException). Operationally, the application will begin to fail every time it accesses the database. The pool might invalidate connections and try to create new ones depending on the configuration.
You would usually approach this gracefully:
- Catch SQL exceptions and display user-friendly messages (such as “Service temporarily unavailable”).
- The pool or container can try to connect again (maxRetry settings are available in some pools). After a while, if the database is down, the pool can get exhausted, and more requests will fail quickly.
- With JTA/CMT, any transactions involving DB would be rolled back and would fail.
Best practice would be to define connection validation and timeouts to eliminate bad connections from the pool. Proper error handling must also be implemented: namely, queue or retry critical updates, use a fallback (such as a message queue), or failover to a standby database where one exists.
47. What is the significance of the Java EE Connector Architecture (JCA) adapter?
The JCA adapter (also known as a resource adapter) is the pluggable piece that fulfills the JCA specification for a given external system. Its value lies in the fact that it gives a standardized integration point between the Java EE container and non-JEE systems (such as legacy EIS, mainframes, ERP, or messaging systems).
With a JCA adapter, you don’t develop proprietary code to connect to, e.g., an SAP system. The vendor ships a resource adapter (as a .rar package). The app server manages it (pools the connection, manages transactions, etc.) using JCA contracts. The JCA adapter to an EIS is essentially like a JDBC driver to a database. It enables JEE apps to use @Resource or JNDI to reference a connection to this system, with the container managing it.
As a result, JCA adapter plays a crucial part in allowing enterprise Java applications to connect to and engage with enterprise systems in a container-managed, portable fashion. It encapsulates EIS complexity while allowing Java EE developers to utilize a homogeneous API.
48. How is a 32-bit JVM different from a 64-bit JVM in enterprise applications?
The major difference between 32-bit and 64-bit JVMs are primarily related to memory addressing and performance:
- Address Space: A 32-bit JVM can address a maximum of about 2–4 GB of heap memory (on most OSes). A 64-bit JVM can access a much, much larger heap (terabytes, in practice). Only a 64-bit JVM can be used for large enterprise applications requiring extremely large heaps (>4GB).
- Pointer Size: In a 64-bit JVM, object references are 64 bits (or 8 bytes) rather than 32 bits (or 4 bytes). This makes data structures containing object references (such as arrays or HashMap) utilize roughly twice the memory for the references.
- Alignment/Overhead: Many 64-bit JVMs use more extensive object alignment (e.g., 32-byte alignment vs. 16-byte in a 32-bit environment), and thus can include more internal padding, further raising memory requirements.
- Performance: A 64-bit JVM can access more registers from the CPU and potentially optimize better, but can pay a small performance penalty from longer pointers and data. In reality, a lot of applications see comparable, if slightly lower, throughput in 64-bit, although newer VMs offset this by using compressed OOPs (shorter pointers) where heaps are not gigantic.
- Compatibility: They both execute the same bytecode, but native libraries have to match (32 vs. 64 bit). A 32-bit JVM executes on a 32-bit OS, while a 64-bit JVM executes on a 64-bit OS.
If memory is limited and your requirements are minimal, a 32-bit JVM can work, but 64-bit is typically preferred now for scalability.
49. What are the differences between Singleton and Stateless EJBs?
Both @Singleton and @Stateless EJBs offer shared functionality, yet in lifecycle and use, they are different:
- Singleton EJB: It means One instance per application (per JVM) exists. That one instance serves every client. The container eagerly creates it or lazily, depending on annotations. Singletons are never passivated (they remain in memory at all times). You can use @PostConstruct within a singleton to initialize once at app startup. Since a single instance exists, concurrency must be treated carefully (e.g., use @Lock annotations). Singletons are suitable for a shared cache, config data, or for startup work (the container invokes them once at startup if annotated with @Startup).
- Stateless EJB: A pool of stateless bean instances can be maintained. You can serve each client call to a stateless bean from any instance from the pool; even the container can use two different instances for two consecutive calls from one client. You do not store client-related state within stateless beans. The pool is managed by the container, which can scale up or down the number of instances. The instance after processing a call, is put back into the pool for reuse by other clients.
Stateless beans are essentially stateless workers, while a singleton is a shared resource. Use stateless beans for stateless, scalable request-handling. Use singletons for shared services or where you want a single point of access (such as a cache).
50. How would you secure a J2EE web application? Discuss best practices.
Securing a J2EE web application covers several layers. Best practices are:
- Use HTTPS at all times: Use TLS (SSL) to encrypt traffic. Make the web container require HTTPS for sensitive URLs (e.g., through web.xml security-constraint).
- Container-Managed Security: Utilize the security model in Java EE. Declare security realms and roles, and guard URLs or methods declaratively (<security-constraint> or annotations such as @RolesAllowed). This shifts authentication/authorization work to the container.
- Authentication and Authorization: Implement strong authentication (form login, integration with LDAP, OAuth, etc.). Use roles to map users through realms, and verify roles in code or config. For EJBs, use @RolesAllowed for access restriction.
- Password Management: Keep passwords encrypted or hashed, not in plain form. Use TLS for login pages.
- Input Validation: Validate all input (both client and server) thoroughly to avert SQL Injection, XSS, and other vulnerabilities. For instance, use prepared statements or JPA parameter binding to prevent SQL injection. Escape or encode output to avert XSS.
- CSRF Protection: Use Cross-Site Request Forgery tokens for state-changing requests to confirm requests are originating from your own forms.
- Session Management: Implement HttpOnly, Secure flags for secure session cookies. Regenerate session IDs after login to avoid fixation. On logout, invalidate sessions.
- Conduct Security Testing: Utilize a tool or manual audit to scan for typical vulnerabilities (OWASP top 10: SQLi, XSS, CSRF, etc.).
You’d use container-configured security (realms, constraints) in conjunction with application code practices (error handling, validation) in practice. You can use Java EE’s own mechanisms (JAAS, JACC) or frameworks like Spring Security. The most important aspect is multi-layer defense: encrypt data in transit, validate data everywhere, require strong auth, and error handling securely (no stack trace to clients).
Conclusion
With this, we have finished this list of top J2EE interview questions and answers, in which we have explained how J2EE skills are in major demand, specifically for those jobs related to scalable web applications, backend architecture, and integration at the enterprise level. Whether you are going for your initial Java developer interview or looking for a senior-level Java architect job, your command over Servlets, JSP, JDBC, JTA, EJB, and associated technologies is not negotiable.
This list of best J2EE interview questions with detailed answers is intended not only to assist you in clearing your interviews, but also to improve your practical knowledge about the Java EE environment.
Also Read:
Top J2EE Interview Questions – FAQs
Frequently Asked Questions
Q1. What job roles can I get with strong J2EE skills?
With J2EE proficiency, you can seek job opportunities in:
- Java Developer
- Backend Developer
- Full Stack Java Developer
- Java/J2EE Software Engineer
- Java Enterprise Architect
- Application Support Engineer (J2EE)
They usually need a good understanding of Servlets, JSP, JDBC, EJB, and newer frameworks such as Spring, Hibernate, and RESTful APIs.
Q2. What is the typical J2EE interview process in top IT companies?
Most companies follow a 3–5 round process:
- Online coding or technical screening (MCQs + coding questions in Java)
- Core Java + J2EE technical round (in-depth knowledge on Servlet lifecycle, EJB, JSP, transaction handling)
- System design or architecture round (for senior roles)
- Behavioural or managerial round
- HR round discussing salary and job fit
Q3. Which top companies actively hire J2EE professionals in India and abroad?
Numerous product and service-based firms regularly recruit J2EE developers, including:
- Tata Consultancy Services, Infosys
- IBM, Accenture, Capgemini, HCL
- Oracle, SAP, Tech Mahindra
- Startups developing large-scale business applications
- Amazon, Dell, Bosch, and Siemens are examples of MNCs for enterprise-level systems
You’ll also see robust demand in BFSI, e-commerce, and telecommunications sectors.
Q4. What is the average salary of a J2EE developer in India and globally?
In India:
- Freshers: ₹3.5 LPA – ₹6 LPA
- 2–5 years experience: ₹6 LPA – ₹12 LPA
- Senior developers/architects: ₹15 LPA – ₹30+ LPA
In the U.S. and Europe:
- Entry level: $70,000 – $90,000/year
- Mid-senior level: $100,000 – $140,000/year
Salaries are significantly higher when J2EE is combined with skills in Spring Boot, Microservices, or cloud platforms such as AWS and Azure.
Q5. Is J2EE still in demand in 2025 and beyond?
Yes, J2EE (now Jakarta EE) continues to be very much in demand, notably for legacy systems, enterprise-level platforms, as well as government initiatives.
Although newer options like Spring Boot and Quarkus are available, numerous large-scale applications continue to use J2EE components for scalability and reliability.
J2EE learning gives entry to Java roles at the enterprise level, migration projects, as well as integration work within large organizations.