Showing posts with label Java EE. Show all posts
Showing posts with label Java EE. Show all posts

Java J2EE Spring Enterprise Java interview questions and answers

The following  most popular enterprise Java (i.e. JEE or J2EE) interview questions and answers are frequently asked in job interviews. If you are a more experienced professional and have a good understanding of the high level basics, then try How does JEE 6 differ from JEE 5?


Q. Explain 3-tier or n-tier architecture  used by JEE?
A. This is a very commonly asked question. Be prepared to draw some diagrams on the board. The JEE platform is a multi-tiered system. A tier is a logical or functional partitioning of a system.


Each tier is assigned a unique responsibility in a 3-tier system. Each tier is logically separated and loosely coupled from each other, and may be distributed.

Client tier represents Web browser, a Java or other application, Applet, WAP phone etc. The client tier makes requests to the Web server who will be serving the request by either returning static content if it is present in the Web server or forwards the request to either Servlet or JSP in the application server for either static or dynamic content.

Presentation tier encapsulates the presentation logic required to serve clients. A Servlet or JSP in the presentation tier intercepts client requests, manages logons, sessions, accesses the business services, and finally constructs a response, which gets delivered to client.

Business tier provides the business services. This tier contains the business logic and the business data. All the business logic is centralized into this tier as opposed to 2-tier systems where the business logic is scattered between the front end and the backend. The benefit of having a centralized business tier is that same business logic can support different types of clients like browser, WAP (Wireless Application Protocol) client, other stand-alone applications written in Java, C++, C# etc.

Integration tier is responsible for communicating with external resources such as databases, legacy systems, ERP systems, messaging systems like MQSeries etc. The components in this tier use JDBC, JMS, J2EE Connector Architecture (JCA) and some proprietary middleware to access the resource tier.

Resource tier is the external resource such as a database, ERP system, Mainframe system etc responsible for storing the data. This tier is also known as Data Tier or EIS (Enterprise Information System) Tier.



Note: On a high level J2EE can be construed as a 3-tier system consisting of Client Tier, Middle Tier (or Application Tier) and Data Tier. But logically or functionally J2EE is a multi-tier (or n-tier) platform.


Q. What are the advantages of a 3-tiered or n-tiered application?
A. 3-tier or multi-tier architectures force separation among presentation logic, business logic and database logic. Let us look at some of the key benefits:

  • Manageability: Each tier can be monitored, tuned and upgraded independently and different people can have clearly defined responsibilities.
  • Scalability: More hardware can be added and allows clustering (i.e. horizontal scaling). 
  • Maintainability: Changes and upgrades can be performed without affecting other components.
  • Availability: Clustering and load balancing can provide availability.
  • Extensibility: Additional features can be easily added.

The following diagram gives you a bigger picture of  the logical tiers and the components.




Q. Explain MVC architecture relating to J2EE?
A. This is also a very popular interview question. MVC stands for Model-View-Controller architecture. It divides the functionality of displaying and maintaining of the data to minimize the degree of coupling (i.e. promotes loose coupling) between components. It is often used by applications that need the ability to maintain multiple views like HTML, WML, Swing, XML based Web service etc of the same data. Multiple views and controllers can interface with the same model. Even new types of views and controllers can interface with a model without forcing a change in the model design.


A model represents the core business logic and state. A model commonly maps to data in the database and will also contain core business logic. 

A view renders the contents of a model. A view accesses the data from the model and adds display logic to present the data.

A controller acts as the glue between a model and a view. A controller translates interactions with the view into actions to be performed by the model. User interactions in a Web application appear as GET and POST HTTP requests. The actions performed by a model include activating business processes  or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.

Q. What are ear, war and jar files? What are J2EE Deployment Descriptors?
A. The ear, war and jar are standard application deployment archive files. Since they are a standard, any application server (at least in theory) will know how to unpack and deploy them.

An EAR file is a standard JAR file with an “.ear” extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file. JAR files can’t have other JAR files. But EAR and WAR (Web ARchive) files can have JAR files.

An EAR file contains all the JARs and WARs belonging to an application. JAR files contain the EJB classes and WAR files contain the Web components (JSPs, Servlets and static content like HTML, CSS, GIF etc). The J2EE application client's class files are also stored in a JAR file. EARs, JARs, and WARs all contain one or more XML-based deployment descriptor(s).

Deployment Descriptors

A deployment descriptor is an XML based text file with an “.xml” extension that describes a component's deployment settings. A J2EE application and each of its modules has its own deployment descriptor.




More related questions and answers at

Spring Framework SOAP versus RESTful Web service -- comparison



Recently I attended an interview with a large investment bank, and I was quizzed on SOAP versus RESTful web service. The interview questions were targeted at ascertaining my understanding of the differences, pros and cons of each, and when to use what.

Web services are very popular and widely used to integrate similar (i.e. Java applications) and disparate systems (i.e. legacy applications and applications written in .Net etc). It is imperative to understand the differences, pros, and cons between each approach.

Key Area
SOAP based Web service
RESTful Web service
Specification/Platform Fundamentals (SF/PF)
Transport is platform & protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP, SMTP, etc.

Permits only XML data format, hence language neutral.


You define operations, which tunnels through the POST or GET. The focus is on accessing the named operations and exposing the application logic as a service.



Defines the contract via WSDL.
Transport is protocol specific. Supports only HTTP or HTTPS protocols.


Permits multiple data formats like XML, JSON data, text, HTML, atom, RSS, etc.

Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE web operations. The focus is on accessing the named resources and exposing the data as a service.

Traditionally, the big drawback of REST was the lack of contract for the web service. This has changed with WSDL 2.0 defining non SOAP bindings and the emergence of WADL.


Simpler to implement. REST has Ajax support. It can use the XMLHttpRequest object.

Good for stateless CRUD (Create, Read, Update, and Delete) operations.

Performance Consideration (PC)
SOAP based reads cannot be cached. The application that uses SOAP needs to provide cacheing.
REST based reads can be cached. Performs and scales better.
Security (SE)
Supports both SSL security and WS-security, which adds some enterprise security features. Supports identity through intermediaries, not just point to point SSL.


WS-Security maintains its encryption right up to the point where the request is being processed.


WS-Security allows you to secure parts (e.g. only credit card details) of the message that needs to be secured. Given that encryption/decryption is not a cheap operation, this can be a performance boost for larger messages.

It is also possible with WS-Security to secure different parts of the message using different keys or encryption algorithms. This allows separate parts of the message to be read by different people without exposing other, unneeded information.

SSL security can only be used with HTTP. WS-Security can be used with other protocols like UDP, SMTP, etc.

Supports only point-to-point SSL security.

The basic mechanism behind SSL is that the client encrypts all of the requests based on a key retrieved from a third party. When the request is received at the destination, it is decrypted and presented to the service. This means the request is only encrypted while it is traveling between the client and the server. Once it hits the server (or a proxy which has a valid certificate), it is decrypted from that moment on.

The SSL encrypts the whole message, whether all of it is sensitive or not.

Transaction Management (TM)
Has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.
REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
Quality of Service (QoS)
SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
Best Practice (BP)
In general, a REST based web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security, transactional reliability and stricter contract.


SOA (Service Oriented Architecture) versus WOA (Web Oriented Architecture)

(Source: )


SOA and WOA differ in terms of the layers of abstraction. SOA is a system-level architectural style that tries to expose business capabilities so that they can be consumed by many applications. WOA is an interface-level architectural style that focuses on the means by which these service capabilities are exposed to consumers. You can start out with a WOA and then grow into SOA.

Spring Hibernate Server side versus client side templating



The modern Rich Internet Applications (RIA) use the design concept of "single page web design", where a single rich page makes ajax based service calls to render different sections of a page instead of the traditional approach of loading a new page of each user action.

The "single page web design" can make use of  client side and server side technologies as discussed below. Each approach has its use. It also shows the power of JavaScript.


Q. What do you understand by client side and server side templating?
A. The modern rich single page web applications built today harness the power of dynamically typed and interpreted languages like JavaScript for faster prototyping and increased developer productivity and statically typed Java based frameworks for maintainability, robustness, easier refactoring, and scalability. The modern browsers using faster JavaScript engines and efficient minification of JavaScript files have made client side templating a reality.

  • The server side templates are such as JSPs, Facelets for JSF, Apache Velocity, tiles, Sitemesh, etc. 
  • The client side templating libraries based on JavaScript include dust.js, underscore.js, mustache.js, etc 
  • The client side and server side templates like Google closure. 

 Server side templating and data composition 

Generates the markup on the server. For example, returns generated HTML code.



Client  side templating and data composition

Generates the markup on the client. More suited for applications that load more data from different back end service providers via ajax. The services could return data in JSON or XML format  and then add the HTML snippets for the new data via the client side templates.




Javascript templating is a technique to render templates on client-side (i.e. within the browser) with Javascript using a JSON data retrieved via RESTful web service calls. The template is basically HTML markup, sprayed with tags and variables that will insert values from the JSON data or execute a programming logic. For example,

1. Import jQuery template library


<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>

2. Define JSON data to be used to fill the template values. This can be returned from the server via a RESTFul service call.

var carsData = [
{ make: "Toyota", model: "Camry" },
{ make: "BMW", model: "3 Series" },
{ make: "Mazda", model: "3" }
];

3. Define your client side template like

<script id="carsTemplate" type="text/html">
<li><a href="cars/${make}">${model}</a></li>
</script>

or the complete HTML code may look like:

<html lang="en">
<head>
...
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>

<script id="clientTemplate" type="text/html">
<li>make: ${make}, model: ${model}</li>
</script>

</head>

<body>

<ul></ul>

</body>
</html>

4. Invoking the template enginge (e.g jQuery) plugin to render the template with data

$("#carsTemplate").tmpl(carsData).appendTo( "ul" );

The  <li> tags will be appended to the <ul> tag with the retrieved JSON data values.


Q. What are the pros and cons of server side versus client side templating?
A. 

 Server Side Templating

Pros:

  • More search engine friendly.
  • Entire response message can be cached.
  • Can work without JavaScript

Cons:

  • Harder to mix and match different server side technologies. For example, retrieve data from both Java and Ruby based services
  • Harder to send content for multiple devices. E.g. browser, mobile devices, etc.


Client Side Templating


Pros:

  •  Faster development and prototyping
  •  Serves JSON data to multiple devices.
  •  The responses are smaller as JSON data is less verbose.
  •  Templates and JSON data can be cached.
  •  Can work with multiple server side technologies like .Net, JEE, Ruby, etc


Cons:

  •  Less search engine friendly
  •  Older browsers may not work properly
  •  Cross browser compatbility testing is required




Java J2EE Spring JSP Interview Questions and Answers

Q. How does JSP differ from a desk top application?
A. Desktop applications (e.g. Swing) are presentation-centric, which means when you click a menu item you know which window would be displayed and how it would look. Web applications are resource-centric as opposed to being presentation-centric. Web applications should be thought of as follows: A browser should request from a server a resource (not a page) and depending on the availability of that resource and the model state, server would generate different presentation like a regular “read-only” web page or a form with input controls, or a “page-not-found” message for the requested resource. So think in terms of resources, not pages.

Servlets and JSPs are server-side presentation-tier components managed by the web container within an application server. Web applications make use of HTTP protocol, which is a stateless request-response based paradigm. JSP technology extends the Servlet technology, which means anything you can do with a Servlet you can do with a JSP as well.



Q. Did JSPs make servlets obsolete? 
A. No. JSPs did not make Servlets obsolete. Both Servlets and JSPs are complementary technologies. You can look at the JSP technology from an HTML designer’s perspective as an extension to HTML with embedded dynamic content and from a Java developer’s as an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(“….. ”) statements, where “out” is a PrintWriter. This process of embedding HTML code with escape characters in Servlets is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.




Q. What is a model 0 pattern (i.e. model-less pattern) and why is it not recommended? What is a model-2  or MVC architecture?
A.

Problem: The example shown above is based on a “model 0” (i.e. embedding business logic within JSP) pattern.  The model 0 pattern is fine for a very basic JSP page as shown above.  But real web applications would have business logic, data access logic etc, which would make the above code hard to read, difficult to maintain, difficult to refactor, and untestable. It is also not recommended to embed business logic and data access logic in a JSP page since it is protocol dependent (i.e. HTTP protocol) and makes it unable to be reused elsewhere like a wireless application using a WAP protocol,  a standalone XML based messaging application etc.       

Solution:  You can refactor the processing code containing business logic and data access logic into Java classes, which adhered to certain standards. This approach provides better testability, reuse and reduced the size of the JSP pages.  This is known as the “model 1” pattern where JSPs retain the responsibility of a controller, and view renderer with display logic but delegates the business processing to java classes known as Java Beans. The Java Beans are Java classes, which adhere to following items:

  • Implement java.io.Serializable or java.io.Externalizable interface.
  • Provide a no-arguments constructor.
  • Private properties must have corresponding getXXX/setXXX methods.


The above model provides a great improvement from the model 0 or model-less pattern, but there are still some problems and limitations.

Problem:  In the model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the user. This architecture may be suitable for simple applications, but complex applications will end up with significant amount of Java code embedded within your JSP page, especially when there is significant amount of data processing to be performed.  This is a problem not only for java developers due to design ugliness but also a problem for web designers when you have large amount of Java code in your JSP pages. In many cases, the page receiving the request is not the page, which renders the response as an HTML output because decisions need to be made based on the submitted data to determine the most appropriate page to be displayed.   This would require your pages to be redirected (i.e. sendRedirect (…)) or forwarded to each other resulting in a messy flow of control and design ugliness for the application. So, why should you use a JSP page as a controller, which is mainly designed to be used as a template?       

Solution: You can use the Model 2 architecture (MVC – Model, View, Controller architecture), which is a hybrid approach for serving dynamic content, since it combines the use of both Servlets and JSPs. It takes advantage of the predominant strengths of both technologies where a Servlet is the target for submitting a request and performing flow-control tasks and using JSPs to generate the presentation layer. As shown in the diagram below, the servlet acts as the controller and is responsible for request processing and the creation of any beans or objects used by the JSP as well as deciding, which JSP page to forward or redirect the request to  (i.e. flow control) depending on the data submitted by the user. The JSP page is responsible for retrieving any objects or beans that may have been previously created by the servlet, and as a template for rendering the view as a response to be sent to the user as an HTML.




Q. If you set a request attribute in your JSP, would you be able to access it in your subsequent request within your servlet code?
    [This question can be asked to determine if you understand the request/response paradigm]
A. The answer is no because your request goes out of scope, but if you set a request attribute in your servlet then you would be able to access it in your JSP.



Important: Servlets and JSPs are server side technologies and it is essential to understand the HTTP request/response paradigm. A common misconception is that the Java code embedded in the HTML page is transmitted to the browser with the HTML and executed in the browser. As shown in the diagram above, this is not true. A JSP is a server side component where the page is translated into a Java servlet and executed on the server. The generated servlet (from the JSP) outputs only HTML  code to the browser.  

As shown above in the diagram, if you set a request attribute in your servlet code, it can be retrieved in your JSP code, since it is still in scope. Once the response has been sent back to the user (i.e. the browser) the current request goes out of scope. When the user makes another request, a new request is created and the request attribute set by the JSP code in your previous request is not available to the new request object.  If you set a session attribute in your JSP, then it will be available in your subsequent request because it is still in scope.  You can access it by calling session.getAttribute(“JSPText”).

Note: The above questions and answers are extracted from my book entitled Java/J2EE Job Interview Companion. Only a few JSP questions and answers are shown.

Spring Hibernate Enterprise Java Interview Questions and Answers: What is new in JEE 6?

It is imperative to keep track of the  key enhancements and improvements to JEE. If you are interested in JEE basics the try Enterprise Java frequently asked questions and answers.


Q. What is new in the Java EE 6  (JEE 6) compared to Java EE 5 (JEE 5)?
A.

  • JEE 6 provides more extensibility points and service provider interfaces to plug into for the service providers. For example, "Java Authentication Service Provider interface Containers" provides a mechanism for the authentication providers to integrate with the containers.
  • JEE 5 favored convention over configuration by replacing XML with annotations and POJOs. The JEE 6 extended POJOs with dependency injection (i.e JSR 299 -- Context and Dependency Injection - CDI). This enables a JSF managed bean component to interact with an enterprise Java bean (i.e. EJB) component model to simplify development. It is about time all various types of managed beans are unified. In Java EE 6, the CDI builds on a new concept called "managed beans", which is managed by the enterprise edition container. In CDI, a managed bean is a Java EE component that can be injected into other components. The specification also provides a set of services like resource injection, lifecycle callbacks, and interceptors.   
  • Any CDI managed component may produce and consume events. This allows beans to interact in a completely decoupled fashion. Beans consume events by registering for a particular event type and qualifier.
  • The JAX-WS stack was overhauled to be an integrated stack with JAX-WS 2.x, JAXB 2.x, SAAJ 1.x, JAX-RS 1.x (new RESTful) and JAXR 1.x. (new pull-parsing API). 
  • Servlet 3.0 spec introduced the Async Servlet, file uploading functionality, and annotations based configuration.The web.xml file is optional.
  • Singleton EJBs  (i.e. one EJB per container) and asynchronous session beans  were introduced. The EJB was streamlined  with fewer classes, interfaces, and simpler object to relational mapping by taking advantage of the JPA.
  • Bean based validation framework was introduced to avoid duplication.
  • Enterprise Java Beans (i.e EJBs) can be packaged directly into a WAR file. No longer required to be packaged as JAR and then included into an EAR.
  • The JSF 2.0 simplifies the development of UI components.The JSF 2.0 has integrated Ajax and CDI support.  
Note: "Convention over configuration" is a design paradigm, which seeks to standardize, simplify, and decrease the number of decisions that developers need to make without compromising on flexibility. For example, ANT build tool allowed you to come up with any project structure, whereas Maven is strict on convention as to how the project is structured.

Q. How does the new bean validation framework avoid duplication?
A. Developers often code the same validation logic in multiple layers of an application, which is time consuming and error-prone. At times they put the validation logic in their data model, cluttering it with what is essentially metadata. JEE 6 Improves validation and duplication with a much improved annotation based bean validation. Bean Validation offers a framework for validating Java classes written according to JavaBeans conventions. You use annotations to specify constraints on a JavaBean. For example,

The JavaBean is defined below

public class Contact {

@NotEmpty @Size(max=100)
private String firstName;

@NotEmpty @Size(max=100)
private String surname;

@NotEmpty @Pattern("[a-zA-Z]+")
private String category;

@ShortName
private String shortName; //custom validation

...

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

...
}

Custom validators can be defined by defining an annotation and relevant implementation

@ConstraintValidator(ShortNameValidator.class)
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface ShortName {
String message() default "Wrong name";
String[] groups() default {};
}



Next the validation implementation class

public class ShortNameValidator implements ConstraintValidator <Contact, String> {

private final static Pattern SHORTNAME_PATTERN = Pattern.compile("[a-zA-Z]{5,30}");

public void initialize(Contact constraintAnnotation) {
// nothing to initialize
}


public boolean isValid(String value, ConstraintValidatorContext context) {
return SHORTNAME_PATTERN.matcher(value).matches();
}

}


You could use the validator as shown below

Contact contact = new Contact();
conatct.setFirstName("Peter");
//.... set other values

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();

Set<ConstraintViolation<Contact>> violations = validator.validate(Contact);



Q. What are the benefits of the asynchronous processing support that was introduced in Servlet 3.0 in JEE 6?
A.

1. If you are building an online chess game or a chat application, the client browser needs to be periodically refreshed to reflect the changes. This used to be achieved via a technique known as the server-polling (aka client pull or client refresh). You can use the HTML tag <META> for polling the server. This tag tells the client it must refresh the page after a number of seconds.

<META http-equiv="Refresh" content="10"; url="newPage.html" />

The URL newPage.html will be refreshed every 10 seconds. This approach has the downside of wasting network bandwidth and server resources. With the introduction of this asynchronous support, the data can be sent via the mechanism known as the server push as opposed to server polling. So, the client waits for the server to push the updates as opposed to frequently polling the server.



2. The Ajax calls are integral part of any web development as it provides richer user experience. This also means that with Ajax, the clients (i.e. browsers) interact more frequently with the server compared to the page-by-page request model. If an Ajax request needs to tap into server side calls that are very time consuming (e.g. report generation), the synchronous processing of these Ajax requests can degrade the overall performance of the application because these threads will be blocked as the servers generally use a thread pool with finite number of threads to service concurrent requests. The asynchronous processing will allow these time consuming requests to be throttled via a queue, and the same thread(s) to be recycled to process queued requests without having to chew up the other threads from the server thread-pool. This approach can be used for non Ajax requests as well.


Note: In JEE 6, The EJB 3.1 can also specify a Session Bean to be asynchronous.



Q. What are benefits of web fragements introduced in Servelt 3.0 spec?
A. Web applications use frameworks like JSF, Struts, Spring MVC, Tapestry, etc. These frameworks normally bootsrap (i.e register) via the web.xml file using the <servlet> and <listener> tags. For example


The web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>
<servlet-name>My JSFServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>My JSFServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>

</web-app>

If a particular application uses more than one framework, the above approach is not modular as you will have to bootstrap all the frameworks within the same web.xml file, making it large and difficult to isolate framework specific descriptors. The Servlet 3.0 specification addresses this issue by introducing web fragments. A web fragment can be considered as one of the segment of the whole web.xml and it can be thought of as one or more web fragments constituting a single web.xml file. The fragment files are stored under /META-INF/web-fragment.xml, and it is the responsibility of the container to scan the fragement files during the server start-up.

The web-fragment.xml file

<web-fragment>
<servlet>
<servlet-name>myFrameworkSpecificServlet</servlet-name>
<servlet-class>myFramework.myFrameworkServlet </servlet-class>
</servlet>

<listener>
<listener-class>myFramework.myFrameworkListener</listener-class>
</listener>
</web-fragment>


Note: The Servlet 3.0 specification also provides enhanced pluggability by providing an option to add servlets, filters, servlet mappings and filter mappings during the run time.


Q. What do you understand by the term "Web profile" in Java EE 6?
A. Java EE 6 introduces the concept of profiles as a way to slimming the footprint of the Java EE platform and better target it for specific audiences. Profiles are configurations of the Java EE platform that are designed for specific classes of applications. For example, the required elements for a Web profile are

  • Java EE 6 (JSR-316)
  • Common Annotations for Java Platform 1.1 (JSR-250)
  • Dependency Injection for Java 1.0 (JSR-330)
  • Contexts and Dependency Injection for Java EE platform 1.0 (JSR-299)
  • Servlet 3.0 (JSR-315)
  • JavaServer Pages (JSP) 2.2 (JSR-245)
  • Expression Language (EL) 2.2 (JSR-245)
  • Debugging Support for Other Languages 1.0 (JSR-45)
  • Standard Tag Library for JavaServer Pages (JSTL) 1.2 (JSR-52)
  • JavaServer Faces (JSF) 2.0 (JSR-314)
  • Enterprise JavaBeans (EJB) 3.1 Lite (JSR-318)
  • Java Transaction API (JTA) 1.1 (JSR-907)
  • Java Persistence API (JPA) 2.0 (JSR-317)
  • Bean Validation 1.0 (JSR-303)
  • Managed Beans 1.0 (JSR-316)
  • Interceptors 1.1 (JSR-318)


The JEE 6 has also introduced the concept known as "pruning" to manage complexities. This is similar to the concept introduced in Java SE 6. Pruning is performed as a multistep process where a candidate is declared in one release but may be relegated to an optional component in the next release, depending on community reaction. For example, JAX-RPC will be pruned and replaced by JAX-WS. However, if Java EE application server vendors do include a pruned technology, they must do so in a compatible way, such that existing applications will keep running. The profiles and pruning are debatable topics and only time will tell if they work or not.

More relevant JEE questions and  answers:

Java J2EE Spring Maven interview questions and answers - inheritance vs aggregation



Q: How do you inherit dependencies or plugins  in Maven? How are sub modules aggregated?
A:

In Maven Inheritance, you will have a multi-module maven project where a centrally managed POM file contains all the “approved” versions of artifacts.  In this “parent” pom was a “dependencyManagement” section with all the preferred versions of libraries within the organization. When you build a child of this parent, Maven will retrieve this parent to merge the parent pom with the child pom. You can have a look to the entire pom.xml by running the command mvn help:effective-pom. This parent pom is also known as the reactor pom. The child modules like myproject-ui, myproject-security, etc will be inheriting the versions from the parent.

Like "dependencyManagement" the "pluginManagement" in parent contains plugin elements intended to configure child project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.

As shown below, the child modules are aggregated. The principle is that every command that you run on on the parent (i.e. reactor pom) will also be run on all the sub-modules. The order of the modules will be defined by the Reactor, which will look at inter-modules dependencies to find which module must be built before the others. If there are no dependencies, then it will take the list of the modules as they are defined in the parent pom.xml.

Parent pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myproject</groupId>
<artifactId>myproject-parent-build</artifactId>
<packaging>pom</packaging>
<version>${myproject.version}</version>
<name>${project.artifactId}</name>
<url>http://www.myorganization.com</url>

<properties>
<myproject.version>1.0.0</myproject.version>
<seam.version>2.2.2.Final</seam.version>
...
</properties>

<dependencyManagement>
<dependencies>
<!-- jboss seam dependencies -->
<dependency>
<groupId>org.jboss.seam</groupId>
<artifactId>jboss-seam</artifactId>
<version>${seam.version}</version>
</dependency>
...
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
...
</plugins>

<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
...
</plugins>
</pluginManagement>
</build>

...

<modules>
<module>myproject-security</module>
<module>myproject-content</module>
<module>myproject-data</module>
<module>myproject-ui</module>
<module>myproject-analytics</module>
</modules>

</project>



Child pom.xml . The parent tag defines the parent to inherit form.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myproject</groupId>
<artifactId>myproject-ui</artifactId>
<version>${myproject.version}</version>
<packaging>war</packaging>
<name>${project.artifactId}</name>
<url>http://www.myorganization.com</url>
<parent>
<groupId>com.myproject</groupId>
<artifactId>myproject-parent-build</artifactId>
<version>${myproject.version}</version>
</parent>

<build>
<finalName>cashonline</finalName>

<pluginManagement>
<plugins>
<plugin>
...
</plugin>
...
</plugins>
</pluginManagement>
</build>

<dependencies>
<dependency>
<groupId>org.jboss.seam</groupId>
<artifactId>jboss-seam</artifactId>
<exclusions>
<exclusion>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
</exclusion>
</exclusions>
</dependency>

...

</dependencies>


</project>


Q. Is this inheritance of dependencies a good idea?
A. It is a good idea when you only have say 5-10 sub modules (i.e. child modules). But, if you have 50+ child modules inheriting from the parent dependency management or plugin management will cause a re-release of anything inheriting from it. For example, if you have 20+ projects inheriting org.jboss.seam jar, and if that jar goes from 2.2.2.Final to 2.3, then you will have to re-release the 20+ projects inheriting from it. It appears that as of version 2.0.9, there is a new scope on a dependency called import to aggregate dependencies without inheriting them.

The example below shows aggregation without the parent tag. The scope "import" aggregates the "myproject-parent-build".

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myproject</groupId>
<artifactId>myproject-ui</artifactId>
<version>${myproject.version}</version>
<packaging>war</packaging>
<name>${project.artifactId}</name>
<url>http://www.myorganization.com</url>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.myproject</groupId>
<artifactId>myproject-parent-build</artifactId>
<version>${myproject.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
....
</dependencies>
</dependencyManagement>


<dependencies>
<dependency>
<groupId>org.jboss.seam</groupId>
<artifactId>jboss-seam</artifactId>
<exclusions>
<exclusion>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
</exclusion>
</exclusions>
</dependency>

...

</dependencies>


</project>


So, like you favor composition or aggregation over inheritance, in maven pom also favor aggregation over inheritance.


Q. What are the different dependency scopes have you used?
A. compile, provided, test, and import.

Compile means that you need the JAR for compiling and running the app. For a web application, as an example, the JAR will be placed in the WEB-INF/lib directory.

Provided means that you need the JAR for compiling, but at run time there is already a JAR provided by the environment so you don't need it packaged with your app. For a web app, this means that the JAR file will not be placed into the WEB-INF/lib directory.

Test scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

import scope is used to aggregate the specified POM with the dependencies in that POM's "dependencyManagement" section. This scope is only used on a dependency of type pom in the section and available only from Maven version 2.0.9.


You could also read other Maven Interview Questions and Answers at Java build tools - why use Maven?

Spring Hibernate Service versus component and SOA versus CBA?



Q. What is the difference between a component and a service?
A. Both components and services are self-contained functionality. Services enable your components to go across language boundary. For example, a component in .Net can talk to a component in Java through generalized messages in XML via Web services (i.e SOAP or RESTFul).

Components are made up of classes, interfaces, and EJBs. Components are used inside the programming boundary. The diagram below shows how you get self contained functionality and re-usability via components and services. Don't confuse yourself with some components being named like portfolio-service. This indicates it is a service layer containing the business logic. The portfolio-dao means portfolio data access object layer. The portfolio-interface contains the domain and POJO classes. These self contained components are used by both portfolio-client.ear, which is a web client and the portfolio-backend.ear, which is the service provider that exposes the business functions as web services across across the language boundaries. A .Net web client can still invoke the RESFul service. But the components in blue can only be used within Java programming boundary. The example shown below is Java based.



It is imperative to understand this difference not only when you are designing a system, but also when you are debugging your application. You need to know where to turn on the debugger for the same component used in 2 different JVM processes. That is the portfolio-client process and the portfolio-backend process. The components in blue are packaged into both deployable (i.e ear) artifacts. Similar color coded diagrams are required to communicate your design to your target audience. The color codes can indicate
  • Shared versus non-shared or reusable versus non-reusable component.
  • New versus existing component.
  • Buy (i.e. third-party ) versus build component. 

When designing a system, think as to

  • How these components are going to be packaged and deployed.
  • Dependencies between the packages and the components. Avoid cyclic dependencies.. 



Q. What is the difference between a Service Orieneted Architecture (SOA) and a Component Based Architecture (CBA) ?
A.  If you work with components, you are predominantly working with the code within the language boundary. For example, classes, interfaces, EJBs, JSF components, JavaScript widgets,  etc. If you work with services, you use some remote functionality over network under some contract. The contract will be in the form of an agreed XML message or JSON data.

Composing services into higher-level processes as in SOA is totally different than linking some components together into an application as in CBA.

A service contract is totally different from a component interface. A component can also offer its functionality over a network via RMI, IIOP, DCOM, CORBA, etc. But if you don't use an EJB as a service, then it's likely to be a component within your JEE application. A component can be exposed as a service. You can take an EJB component and expose it as a web service.

As the industry is moving from application oriented architecture to SOA, where the applications are looked at as a set of services and components working together in fulfilling a certain business need.This is known as the SOBA (Service Oriented Business Applications). The services can be built with varying technologies like JEE, .Net, Ruby, etc. This architecture is used with the "single page web design".

Q. What is a Service Component Architecture (SCA)?
A.  The programming model that specifies how to create and implement services, how to reuse services, and how to assemble or compose services into solutions is achieved via SCA (Service Component Architecture). According to wikepedia, Service Component Architecture (SCA) is a software technology created by major software vendors including IBM and Oracle. SCA provides a model for composing applications that follow Service-Oriented Architecture principles.


SCA encourages organization of business application code based on components that implement business logic, and extend their capabilities through service-oriented interfaces to allow other components to consume functions through the service-oriented interfaces, called service references. SCA divides up the steps in building a service-oriented application into two major parts:
  • The implementation of service components  that provide services and consume other services.
  • The assembly of sets of components to build business applications, through the wiring of service references to services.


Note: If you are aspiring to be an architect, read up more on SCA (Service Component Architecture).


Java J2EE Spring Servlets interview questions and answers

Q. How do you get your servlet to stop timing out on a really long database query?
A. There are situations despite how much database tuning effort you put into a project, there might be complex queries or a batch process initiated via a Servlet, which might take several minutes to execute. The issue is that if you call a long query from a Servlet or JSP, the browser may time out before the call completes. When this happens, the user will not see the results of their request. There are proprietary solutions to this problem like asynchronous servlets in WebLogic, Async Beans in WebSphere etc but you need a solution that is portable. Let us look at portable solutions to this issue.



Solution 1: Client-pull or client-refresh (aka server polling): You can use the tag for polling the server. This tag tells the client it must refresh the page after a number of seconds.

<META http-equiv=”Refresh” content=”10; url=”newPage.html” />


Once you can have the browser poll your Servlet on a regular basis to re-fetch a page, then your servlet can check for a value of a variable say in a HttpSession to determine if the page returned will have the results expected by the user or resend the tag with a “Please wait …” message and retry fetching the page again later.

Solution 2: JEE Solution: Instead of spawning your own threads within your Servlet, you could use JMS (Java Messaging Service). This involves following steps:

  1. You need to have two servlets, a RequestingServlet and a DisplayingServlet. The initial client request is sent to the RequestingServlet. Both the RequestingServlet and DisplayingServlet polled by the browser via tag discussed above or JavaScript. Both these Servlets should send the tag with their responses until final display of the query results.
  2. RequestingServlet places the query on the “request” queue using JMS.
  3. You need to have a MessageDrivenBean (aka MDB) say QueryProcessorMDB, which dequeues the query from the “request” queue and performs the long-running database operation. On completion of processing long-running database operation, the QueryProcessorMDB returns the query results to the “reply” queue (use javax.jms.QueueSender & javax.jms.ObjectMessage). Note: MDBs are invoked asynchronously on arrival of messages in the queue.
  4. DisplayingServlet checks the “reply” queue for the query results using JMS (use javax.jms.QueueReceiver & javax.jms.ObjectMessage) every few seconds via tag described above or a JavaScript.

Advantages: Firstly, implementing your long-running database operation to be invoked from onMessage( ) method of your QueryProcessorMDB decouples your application whereby if a database failure occurs, the request query message will be placed back in the “request” queue and retried again later. Secondly MDBs can be clustered (with or without additional JVMs) to listen on the same “request” queue. This means cluster of MDBs will be balancing the load of processing long running database operations. This can improve the throughput due to increased processing power.


Q. What is the difference between forwarding a request and redirecting a request?
A. Both methods send you to a new resource like Servlet, JSP, etc



Forward:
  • Forward action takes place within the server without the knowledge of the browser. Accepts relative path to the servlet or context root.
  • No extra network trip.

Redirect:
  • Sends a header back to the browser, which contains the name of the resource to be redirected to. The browser will make a fresh request from this header information. Need to provide absolute URL path.
  • This has an overhead of extra remote trip but has the advantage of being able to refer to any resource on the same or different domain and also allows book marking of the page.
Q. What are the considerations for servlet clustering?
A.

  • Objects stored in a session should be serializable to support in-memory replication of sessions. Also consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable.
  • Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate requests.
  • Avoid using instance and static variables in read and write mode because different instances may exist on different JVMs. Any state should be held in an external resource such as a database. 
  • Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs.
  • Avoid using java.io.* because the files may not exist on all backend machines. Instead use getResourceAsStream().


Q. How do you perform I/O operations in a Servlet/JSP?
A.

Problem: Since web applications are deployed as WAR files on the application server’s web container, the full path and relative paths to these files vary for each server.

Solution -1: You can configure the file paths in web.xml using tags and retrieve file paths in your Servlets/JSPs. But this technique requires changes to the web.xml deployment descriptor file, to point to the correct path.


Solution -2: You can overcome these configuration issues by using the features of java.lang.ClassLoader and javax.servlet.ServletContext classes. There are various ways of reading a file using the ServletContext API methods such as getResource(String resource),getResourceAsStream(String resource), getResourcePaths(String path) and getRealPath(String path). The getRealPath(String path) method translates virtual URL into real path.


//Get the file “products.xml” under the WEB-INF folder of  your application as inputstream
InputStream is = config.getServletContext().getResourceAsStream(“/products.xml”);

Alternatively you can use the APIs from ClassLoader as follows. The file “products.xml” should be placed under WEB-INF/classes directory where all web application classes reside.

//Get the URL for the file and create a stream explicitly 
URL url = config.getServletContext().getResource(“/products.xml”);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream));
OR
//use the context class loader
URL url = Thread.currentThread().getContextClassLoader().getResource(“products-out.xml”);
BufferedWriter bw = new BufferedWriter(new FileWriter(url.getFile());


Q. How do you send a file to a browser from your web application? I.e. how do you download a file from your web application?
A. Files can be downloaded from a web application by using the right combination of headers.

//set the header to a non-standard value for attachments to be saved by the browser with the //Save-As dialog so that it is unrecognized by the browsers because often browsers try to do //something special when they recognize the content-type. 
response.setContentType(“application/x-download”);
//use Content-Disposition “attachment” to invoke “Save As” dialog and “inline” for displaying //the file content on the browser without invoking the “Save As” dialog.
response.setHeader(“Content-disposition”, “attachment;filename=” + fileName);


Q. How do you send a file from a browser to your web application? i.e. How do you upload a file to your web application?
A. There are better and more secured ways to upload your files instead of using using web. For example FTP, secure FTP etc. But if you need to do it via your web application then your default encoding and GET methods are not suitable for file upload and a form containing file input fields must specify the encoding type “multipart/form-data” and the POST method in the
tag as shown below:

<form enctype=”multipart/form-data” method=”POST”  action=”/MyServlet”>
<input type=”file” name=”products” />
<input type=”submit” name=”Upload” value=”upload” />
</form>

When the user clicks the “Upload” button, the client browser locates the local file and sends it to the server using HTTP POST. When it reaches your server, your implementing servlet should process the POST data in order to extract the encoded file. Unfortunately, application servers implementing the Servlet and JSP specifications are not required to handle the multipart/form-data encoding. Fortunately there are number of libraries available such as Apache Commons File Upload, which is a small Java package that lets you obtain the content of the uploaded file from the encoded form data. The API of this package is flexible enough to keep small files in memory while large files are stored on disk in a “temp” directory. You can specify a size threshold to determine when to keep in memory and when to write to disk.

Note: The above questions and answers are extracted from the book Java/J2EE Job Interview Companion. Only a few questions and answers are extracted.

Spring Hibernate Why good API design matters?



Q. Why is a good API design important?
A.The Application Programming Interfaces (i.e. APIs) are fine grained services/libraries used by other applications, systems and libraries. A good API design improves flexibility, stability, and extendability of your application.

Now a days, applications are built as reusable components or services. A single page rich web page invoking multiple back end services via ajax  calls is very common. Services are used to put information into cloud storage, retrieving data from cloud storage,  validating data, updating a cloud based database, etc. This makes it even more important to carefully design your API.

Q. Give examples of a bad and good API designs in core Java API?
A. Here are some examples from Core Java API.

Bad Designs:
  • The Java Date and Calendar APIs are inconsistent and unintuitive. Firstly, it's full of deprecated methods and secondly, it makes it hard to do simple date operations. The Date and the Calendar classes are very complicated. Use the Joda Time API as it is well designed and easier to use.
  • Some of the legacy classes, which has synchronized methods everywhere are extended by other classes. For example, The Properties class extends the Hashtable, Stack extends the Vector class, etc.
Good Designs:
  • The Joda Time Library. This will be added to Java 7.
  • The Java Collection API. 

Q. What are some of the key considerations for a good API design
A. 

1. Define task oriented APIs

It is easier to add new methods. Deleting methods will break your client code or service consumers and deprecating methods can make your API more complicated to use.  Hence, favor fine-grained APIs that does a particular task. This also means you need to invoke many API methods to get the desired behaviour. When you are making remote calls over web services or cloud services, the performance may be adversely impacted. Good design is more important than just coding for performance. Premature optimization of code is an anti pattern. In rare instances where your profiling indicate performance issues, expose a number of fine grained services as a new coarse grained service. Remember -- it is easier to add new methods/services than deleting or deprecating existing methods/services. For example

When designing APIs, always think of the caller.

  • How will the caller use the API? 
  • Are method names and signatures intuitive enough for the caller? 

For example 

Bad design: A single method does too many things. The method name and signatures are ambiguous

public interface CashService { 
BigDecimal getBalance (CustomerAccount account, BigDecimal currentBalance, List<TransactionDetail> txnDetails,
boolean includeIncome, boolean includePending, boolean includeUnconfirmed) throws CashBalanceException;
}

Better design: Finegrained APIs that does a particular task. No ambiguous boolean flags or method names.

public interface CashService {

BigDecimal getAvailableBalance (CustomerAccount account) throws CashBalanceException;

BigDecimal getAutocashAvailableBalance ( BigDecimal currentBalance, List<TransactionDetail> txnDetails) throws CashBalanceException;

BigDecimal getPortfolioBalance (BigDecimal portfolioBalance, List<TransactionDetail> txnDetails) throws CashBalanceException;;

BigDecimal getRealtimeAvailableBalance (BigDecimal realtimeBalance, List<TransactionDetail> txnDetails) throws CashBalanceException;

}

The public interface methods defined above could internally (i.e. in the implementation) use a number of reusable private methods to perform the calculation. When exposing functionalities via a public interface, take a minimalistic approach to expose only those methods that will be required by the caller. Remember: it is easier to add methods than to remove.




2. Instead of the boolean flags use the type safe enum. The boolean true/false flags are ambiguous.

Bad design: boolean flags make the API difficult to understand

public interface UserService { 
User getUser (String firstName, String surname, boolean isActive, boolean isMale, boolean ignoreSex) throws UserException;
}

Better design: the enum can take on the values like ACTIVE_MALE, ACTIVE_FEMALE, INACTIVE_MALE, INACTIVE_FEMALE, etc. As the method can take an array of user types with the varargs feature.

public interface UserService { 
User getUser (String firstName, String surname, UserType...type) throws UserException;
}

3. Instead of passing many individual arguments corrupting the method signature, pass a well defined object that wraps all the required values.


public interface UserService { 
User getUser (User user) throws UserException;
}
Where the User object looks like

public class User implements Serializable{

private String firstName;
private String surname;
private UserType[] userTypes.
  //other attributes

//getter and setters

//toString(...), equals(...), hashCode() methods
}

4. If you are using other collection types like List, Set, etc, make sure that you use generics as it makes it clear as to what type of object is stored. E.g. List<User>, Set<usertype>, etc.

5. Your API design must include the precondition check. The method implementation must fail fast after validating the relevant input. For example,

public User getUser (User user) throws UserException {

if(user == null && (StringUtils.isEmpty(user.getFirstName()) || StringUtils.isEmpty(user.getSrurname()) ){
throw new UserException("Invalid input: " + user);
}


....

}

6. Providing good exception/error handling is essential to give the developers using your API an opportunity to correct their mistakes. Error messages should be clear and concise. Messages such as “Invalid input” are highly unhelpful. Also, avoid using a single exception object covering a number of very different possible errors. The decision to throw an exception, an error code, or a value like null to indicate "value is not found" must be carefully considered.

public User getUser (User user) throws UserException {

if(user == null && (StringUtils.isEmpty(user.getFirstName()) || StringUtils.isEmpty(user.getSrurname()) ){
throw new UserException("User's firstName and surname are required. Invalid input: " + user + "");
}


....

}

In the above code, if an input validation fails it makes sense to throw an exception to indicate that an invalid input is supplied. It does not make sense to throw an exception if the designer anticipates that looking for a user that isn't there is not a common case and likely to indicate something that the caller would deal with the condition by substituting with a default "guest user" or prompting the user to register. In this case, returning a null value will be appropriate as this is not an exceptional condition. So, knowing the context in which an API is going to be used will allow you to make the right choice as to throw an exception or not. If your API requires a user to be present before it performs a task, then it makes more sense to throw a "UserNotFoundException".

With careful design of types and parameters, errors can often be caught at compile time instead of being delayed until runtime. Having said this, exceptions compared to true/false and error codes have several important advantages:


  • Exceptions cannot be ignored. If your code throws an exception the caller has to catch it to avoid getting an unhanded exception. The error codes or true/false can be ignored.
  • Exceptions can be handled at a higher level than the immediate caller. If you use error codes you may end up in situations where you at all layers of you application have to check for errors and pass them back to the caller. So, error codes are more appropriate at the highest layer. 


What ever technique you use, be consistent in your approach. Decide early on whether to use a checked or unchecked exception. If planning to use both, clearly have a plan as to when to use a checked exception and when to use an unchecked exception.

J2EE Spring Hibernate Java and Enterprise Java Interview Questions

Here are some frequently asked Java and J2EE Interview Questions with hints. You must at least be prepared with these most popular Java and J2EE interview questions.

Multi-threading  Interview Questions
  • What language features are available to allow shared access to data in a multi-threading environment? (Hint: Synchronized block,Synchronized method,wait, notify)
  • What is the difference between synchronized method and synchronized block?
    (Hint:Block on subset of data. Smaller code segment).
  • What Java language features would you use to implement a producer (one thread) and a consumer (another thread) passing data via a stack? (Hint: wait, notify)

Java language Interview Questions
  • What Java classes are provided for date manipulation? (Hint:Calendar, Date)
  • What is the difference between String and StringBuffer? (Hint: mutable, efficient)
  • How do you ensure a class is Serializable? (Hint:Implement Serializable)
  • What is the difference between static and instance field of a class? (Hint:Per class vs. Per Object)
  • What methods do you need to implement to store a class in Hashtable or HashMap? (Hint: hashCode(), equals()) .
  • How do you exclude a field of a class from serialization? (Hint: transient)


Inheritance Interview Questions
  • What is the difference between an Interface and an abstract base class? (Hint: interface inheritance, implementation inheritance.) What about overloading? (Hint: different signature)
  • What does overriding a method mean? (Hint: Inheritance)

Java Memory Management Interview Questions
  • What is the Java heap, and what is the stack? (Hint: dynamic, program thread execution.)
    Why does garbage collection occur and when can it occur? (Hint: To recover memory, as heap gets full.)
  • If I have a circular reference of objects, but I no longer reference any of them from any executing thread, will these cause garbage collection problems? (Hint: no)

Java Exceptions Handling Interview Questions  
  • What is the difference between a runtime exception and a checked exception? (Hint: Must catch or throw checked exceptions.)
  • What is the problem or benefit of catching or throwing type “java.lang.Exception”? (Hint: Hides all subsequent exceptions.)


Web components

JSP Interview Questions
  • What is the best practice regarding the use of scriptlets in JSP pages? Why? (Hint: Avoid)How can you avoid scriptlet code? (Hint:custom tags, Java beans)
  • What do you understand by the term JSP compilation? (Hint: compiles to servlet code)
Servlets Interview Questions
  • What does Servlet API provide to store user data between requests? (Hint: HttpSession)
  • What is the difference between forwarding a request and redirecting? (Hint: redirect return to browser )
  • What object do you use to forward a request? (Hint: RequestDispatcher)
  • What do you need to be concerned about with storing data in a servlet instance fields? (Hint: Multi-threaded.)
  • What’s the requirement on data stored in HttpSession in a clustered (distributable) environment? (Hint: Serializable)
  • If I store an object in session, then change its state, is the state replicated to distributed Session? (Hint: No, only on setAttribute() call.)
    How does URL-pattern for servlet work in the web.xml? (Hint: /ddd/* or *.jsp)
  • What is a filter, and how does it work? (Hint: Before/after request, chain.)

Enterprise Java

JDBC Interview Questions
  • What form of statement would you use to include user-supplied values? (Hint: PreparedStatement)
  • Why might a preparedStatement be more efficient than a statement? (Hint: Execution plan cache.)
  • How would you prevent an SQL injection attack in JDBC? (Hint: PreparsedStatement )
  • What is the performance impact of testing against NULL in WHERE clause on Oracle? (Hint: Full table scan. )
  • List advantages and disadvantages in using stored procedures? (Hint: Pro: integration with existing dbase, reduced network trafficCon: not portable, mutliple language knowledge required )
  • What is the difference between sql.Date, sql.Time, and sql.Timestamp? (Hint: Date only, time only, date and time )
  • If you had a missing int value how do you indicate this to PreparedStatement? (Hint: setNull(pos, TYPE))
  • How can I perform multiple inserts in one database interaction? (Hint: executeBatch)Given this problem: Program reads 100,000 rows, converts to Java class in list, then converts list to XML file using reflection. Runs out of program memory. How would you fix? (Hint: Read one row at time, limit select, allocate more heap (result set = cursor) )
  • How might you model object inheritance in database tables? (Hint: Table per hierarchy, table per class, table per concrete class)
JNDI Interview Questions
  • What are typical uses for the JNDI API within an enterprise application? (Hint: Resource management, LDAP access)
  • Explain the difference between a lookup of these “java:comp/env/ejb/MyBean” and “ejb/MyBean”? (Hint: logical mapping performed for java:comp/env )
  • What is the difference between new InitialContext() from servlet or from an EJB? (Hint: Different JNDI environments initialized EJB controller by ejb-jar.xml, servlet by web.xml.)
  • What is an LDAP server used for in an enterprise environment? (Hint: authentication, authorization)
  • What is authentication, and authorization? (Hint: Confirming identity, confirming access rights )
EJB Interview Questions

  • What is meant by a coarse-grained and a fine-grained interface? (Hint: Amount of data transferred per method call)
  • What is the difference between Stateless and Stateful session beans (used?) (Hint: Stateful holds per client state )
  • What is the difference between Session bean and Entity bean (when used?) (Hint: Entity used for persistence )
    With Stateless Session bean pooling, when would a container typically take a instance from the pool and when would it return it? (Hint: for each business method )
  • What is the difference between “Required”, “Supports”, “RequiresNew” “NotSupported”, “Mandatory”, “Never”? (Hint: Needs transaction, existing OK but doesn’t need, must start new one, suspends transaction, must already be started, error if transaction)
  • What is “pass-by-reference” and “pass-by-value”, and how does it affect J2EE applications? (Hint: Reference to actual object versus copy of object. RMI pass by value.)
    What EJB patterns, best practices are you aware of? Describe at least two? (Hint: Façade, delegate, value list, DAO, value object).
  • Describe some issues/concerns you have with the J2EE specification? (Hint: Get their general opinion of J2EE)
    What do you understand by the term “offline optimistic locking” or long-lived business transaction? How might you implement this using EJB? (Hint: version number, date, field comparisons.)
  • Explain performance difference between getting a list of summary information (e.g. customer list) via finder using a BMP entity vs. Session using DAO? (Hint: BMP: n+1 database reads, n RMI calls.)

XML/XSLT Interview Questions
  • What is the difference between a DOM parser and a SAX parser? (Hint: DOM: reads entire model, SAX: event published during parsing.)
  • What is the difference between DTD and XML Schema? (Hint: level of detail, Schema is in XML.)
  • What does the JAXP API do for you? (Hint: Parser independence. )What is XSLT and how can it be used? (Hint: XML transformation. )
  • What would be the XPath to select any element called table with the class attribute of info? (Hint: Table[@class=’info’])

JMS Interview Questions
  • How can asynchronous events be managed in J2EE? (Hint: JMS)
  • How do transactions affect the onMessage() handling of a MDB? (Hint: Taking off queue. )
  • If you send a JMS message from an EJB, and transaction rollback, will message be sent? (Hint: yes)
  • How do you indicate what topic or queue MDB should react to? (Hint: deployment descriptor )
  • What is the difference between a topic and a queue? (Hint: broadcast, single)

SOAP Interview Questions
  • What is a Web service, and how does it relate to SOAP? (Hint: SOAP is the protocol.)
  • What is a common transport for SOAP messages? (Hint: HTTP )
  • What is WSDL? How would you use a WSDL file? (Hint: XML description of Web Service: interface and how to bind to it. )
  • With new J2EE SOAP support what is: JAXR, JAX-RPC, and SAAJ? (Hint: registry, rpc, attachments)
Java Security Interview Questions

  • Where can container level security be applied in J2EE application? (Hint: Web Uri’s, EJB methods)
  • How can the current user be obtained in a J2EE application (Web and Enterprise)? (Hint: getUserPrincipal, getCallerPrincipal
  • How can you perform role checks in a J2EE application (Web and enterprise)? (Hint: IsUserInRole(), IsCallerInRole() )


Design Interview Questions
  • Name some types of UML diagrams? (Hint: class, sequence, activity, use case)
  • Describe some types of relationships can you show on class diagrams? (Hint: generalization, aggregation, uses)
  • What is the difference between association, aggregation, and generalization? (Hint: Relationship, ownership, inheritance)
  • What is a sequence diagram used to display? ( Hint: Object instance interactions via operations/signals)What design patterns do you use. Describe one you have used (not singleton)? (Hint: e.g. Builder, Factory, Visitor, Chain of Command )
  • Describe the observer pattern and an example of how it would be used (Hint: e.g. event notification when model changes to view )
  • What are Use Cases? (Hint: Define interaction between actors and the system )What is your understanding of encapsulation? (Hint: Encapsulate data and behavior within class )
  • What is your understanding of polymorphism? (Hint: Class hierarchy, runtime determine instance )
Development Process Interview Questions
  • Have you heard of or used test-driven development? (Hint: e.g. XP process )
  • What development processes have you followed in the past? (Hint: Rational, XP, waterfall )
  • How do you approach capturing client requirements? (Hint: Numbered requirements, use cases )
  • What process steps would you include between the capture of requirements and when coding begins? (Hint: Architecture, Design, UML modeling, etc )
  • How would you go about solving performance issue in an application? (Hint: Set goals, establish bench, profile application, make changes one at a time )
  • What developer based testing are you familiar with (before system testing?) (Hint: Unit test discussion )
  • How might you test a business system exposed via a Web interface? (Hint: Automated script emulating browser)
  • What is your experience with iterative development? (Hint: Multiple iteration before release)

Distributed Application Interview Questions
  • Explain a typical architecture of a business system exposed via Web interface? (Hint: Explain tiers (presentation, enterprise, resource) Java technology used in each tiers, hardware distribution of Web servers, application server, database server )
  • Describe what tiers you might use in a typical large scale (> 200 concurrent users) application and the responsibilities of each tier (where would validation, presentation, business logic, persistence occur). (Hint: Another way of asking same question as above if their answer wasn’t specific enough)
  • Describe what you understand by being able to “scale” an application? How does a J2EE environment aid scaling? (Hint: Vertical and Horizontal scaling. Thread management, clustering, split tiers )
  • What are some security issues in Internet based applications? (Hint: authentication, authorization, data encryption, denial service, xss attacks, SQL injection attacks )
General Interview Questions
  • What configuration management are you familiar with? (Hint: e.g. CVS, ClearCase )
  • What issue/tracking process have you followed? (Hint: Want details on bug recording and resolution process).
  • What are some key factors to working well within a team? (Hint: Gets a view on how you would work within interviewer’s environment.)
  • What attributes do you assess when considering a new job? (what makes it a good one)? (Hint: Insight into what motivates you.)
  • What was the last computing magazine you read? Last computing book?
  • What is a regular online magazine/reference you use? (Hint: Understand how up to date you keep yourself.)

Note: You will find answers to all of the above questions in the 400+ Java/J2EE Interview Questions and Answers companion book.

Labels

.equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()