Advanced Java Interview Questions
This section discusses some important questions from the Advanced Java domain with their best possible answers. I hope this will help you to prepare well for any interview on Advanced Java. I wish you best of luck.
1. What are Java Servlets?
Answer: Java Servlets provide a dynamic, component-based, platform-independent technique for developing web-based applications, without the performance limitations of CGI (e.g. Perl, C++ etc.) programs. Servlets are the foundations of web application development using Java and they provide web developers with a simple, consistent mechanism for extending the functionality of a web server and for accessing existing business systems. They have access to the entire family of Java APIs, including the JDBC API to access enterprise RDBMSs (e.g. Oracle, IBM DB2, MS SQL Server, MySQL, MS Access, SAP Adaptive Server Enterprise etc.).
2. What are the advantages of Servlets over CGI?
Answer: The traditional way to add functionality to a web server is the Common Gateway Interface (CGI), a language-independent interface that allows a server to start an external process which acquires information about a request through environment variables, the command line and its standard input stream and writes response data to its standard output stream. Each request is answered in a separate process by a separate instance of the CGI program, or CGI script (written in Perl or C++). Java Servlets have several advantages over CGI programs:
- A Servlet does not run in a separate process (instead it creates thread). This eliminates the overhead of creating a new process for each HTTP request.
- A Servlet stays in memory between client requests. A CGI program should be loaded and started for each CGI request.
- There is only a single instance which responds to all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
- A Servlet can be run by a Servlet engine (i.e. Servlet container) in a restrictive sandbox (similar to an Applet that runs in a web browser’s sandbox) which allows secure use of untrusted and potentially harmful Servlets.
3. What is a Servlet Container?
Answer: The specialized module in the Web server which is dedicated to Servlet management is called Servlet container. The Servlet container is a compiled, executable program. The container is the intermediary between the Web server and the Servlets in the container. The container loads, initializes, and executes the Servlets. When a request arrives, the container maps the request to a Servlet, and then passes the request to the Servlet. The Servlet processes the request and produces a response. The container translates the response into the network format, and then sends the response back to the Web server. Apache Tomcat is an example of a Servlet container. Figure 1 below shows the architecture of a Servlet container.
Figure 1: Architecture of a Servlet Container
4. Explain Servlet life cycle in brief.
Answer: The life cycle of a Java Servlet is determined by three of its methods: init(), service(), and destroy(). The life cycle starts when Servlet container instantiates the object of Servlet class and calls the init() method, and process the request using service() method and ends with the web container calling the destroy() method. The different phases of the Servlet life cycle are shown below:
Figure 2: Different phases of Servlet life cycle
(1) Loading, instantiation and initialization:
When we start up a Servlet container, it looks for a set of configuration files, also called the deployment descriptors that describe all the web applications. Each web application has its own deployment descriptor file, web.xml, which includes an entry for each of the Servlets it uses. The Container first loads the corresponding Servlet class and creates an instance of this class using the method Class.forName(className).newInstance(). Then the Servlet container creates the ServletConfig object, which contains the configuration values stated in the web.xml file for this application and uses it to pass the Servlet initialization parameters to the init() method. The initialization parameters persist until the Servlet is destroyed and are applied to all invocations of that servlet. The Servlet container calls this init() method exactly once.
If the initialization is successful, the Servlet is available for service. If the initialization fails, the Servlet container unloads the Servlet. In such cases, the web application and the Servlet remain unavailable until the administrator changes them to be available.
The signature of init() method is shown below:
public void init (ServletConfig config) throws ServletException
This method also can throw a ServletException. The servlet container cannot place the Servlet into service if the init method throws a ServletException or the method does not return within a time period defined by the web server.
(2) Processing requests:
After the Servlet instance is properly initialized, it is ready to service client requests. When the servlet container receives requests for this Servlet, it will dispatch them to the Servlet instance by calling the Servlet.service (ServletRequest, ServletResponse) method. The Servlet container passes a ServletRequest object and the ServletResponse object. The ServletRequest object contains the client’s request and the ServletResponse contains the Servlet’s response. For HttpServlet, the service() method is basically replaced by doGet() or doPost().
The signature of service() method is shown below:
public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException
The service() method throws a ServletException if an exception occurs that interferes with the Servlet’s normal operation. The service() method also can throw an IOException if an input or output exception occurs during the execution of this method.
The Servlet container unloads a Servlet class by invoking the Servlet’s destroy() method. Typically, this method is invoked when the Servlet container is stopping a web application which contains the Servlet. The method runs only once during the lifetime of the Servlet and signals the end of the Servlet. After a Servlet’s destroy() method is invoked, the Servlet container unloads the Servlet, and the JVM eventually performs garbage collection on the memory resources associated with the Servlet.
The signature of destroy() method is shown below:
public void destroy()
5. What do you mean by preloading and lazy loading?
Answer: Usually, a Servlet container does not initialize the Servlets as soon as it starts up. It initializes a Servlet when it receives a request for that Servlet for the first time. This is called lazy loading. Although this process greatly improves the startup time of the Servlet container, it has a drawback. If the Servlet performs many tasks at the time of initialization, such as caching static data from a database on initialization, the client that sends the first request will have a poor response time. In many cases, this is unacceptable.
The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. This process of loading a servlet before any request comes in is called preloading, or pre-initializing, a Servlet.
6. What is Servlet API?
The Java Servlet API is a class library for Servlets. Servlets are Java programs that run on the server and send response to the client. Two packages are available: javax.servlet and javax.servlet.http.
The first one contains basic classes and interfaces that we can use to write Servlets from the scratch. The second package offers more advanced classes and interfaces that extend classes and interfaces from the first package. It is much more convenient to program using the second package.
The Servlet API packages are listed below.
The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container.
The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container.
7. Explain the working principle of Servlet with detailed architecture?
Answer: A Servlet is loaded by the Servlet container the first time the it is requested. The Servlet then is forwarded the user request, processes it (there may be some database processing), and returns the response to the Servlet container, which in turn sends the response back to the user. After that, the Servlet stays in memory waiting for other requests—it will not be unloaded from the memory unless the Servlet container detects a shortage of memory. Each time the Servlet is requested, however, the Servlet container compares the timestamp of the loaded servlet with the Servlet class file. If the class file timestamp is more recent, the Servlet is reloaded into memory. This way, we don’t need to restart the Servlet container every time we update our Servlet. The whole process is shown in Figure 3 below.
Figure 3: Servlet detailed architecture
Steps are given below —
- The client (web browser) makes a request via HTTP protocol.
- The web Server receives the request and forwards it to the servlet.
- The servlet will receive the request and perform some processing (database call).
- The servlet will return a response back to the web Server.
- The web server will forward the response to the client in terms of HTML output.
8. Differentiate between ServletConfig and ServletContext.
Answer: A web container uses two important concepts in the deployment descriptor (i.e. web.xml) related to the web application development. They are namely: ServletConfig and ServletContext. The differences are listed below.
(1) ServletConfig is one for each Servlet or JSP.
(1) ServletContext is one for each web application.
(2) The Servlet init parameters (i.e. elements) are placed within the element for each Servlet or JSP.
(2) The Servlet context parameters (i.e. elements) are placed within the element but not within a specific element.
(3) Code for accessing Servlet init parameter is:
(3) Code for accessing Servlet context parameter is:
9. Why is HTTP stateless? How is statelessness of HTTP overcome to run e-Commerce applications?
Answer: The Hypertext Transfer Protocol (HTTP) is the protocol that web server and web browser uses to communicate with each other. HTTP connections are initiated by a client browser that sends an HTTP request. The web server then responds with an HTTP response and closes the connection. If the same client requests another resource from the server, it must open another HTTP connection to the server. Server always closes the connection as soon as it sends the response, whether or not the browser user needs some other resource from the server. That is why HTTP is said to be stateless protocol. Being stateless has huge implications. HTTP treats each request as a request from new user. But it is not expected when we are doing any type of transactions or any other related work where persistence of information is necessary. As a result, it is difficult to implement web sites that react intelligently to the user input.
In order to have stateful communication for running e-Commerce applications on the web, the web site developers must make some necessary arrangements for the server to send the state (or some representative of the state) to the client, and for the client to send it back again next time. This is called session management which is being supported by Servlet/JSP. There are four ways this happens in HTTP. One is using session objects, in which case the state is sent and returned in HTTP headers. The second technique is called cookies which are small bits of textual information that a web server sends to a browser and that browser returns the cookie when it visits the same site again. In cookie, the information is stored in the form of a name-value pair. The third one is URL rewriting, in which case the state is sent as part of the response and returned as part of the request URI. The fourth is hidden form fields, in which the state is sent to the client as part of the response, and returned to the server as part of a form’s data (which can be in the request URI or the POST body, depending on the HTML form’s method).
10. What is JSP?
Answer: JavaServer Pages (JSP) is a server-side programming technology that allows the creation of dynamic, platform-independent technique for developing web-based applications. JSPs have access to the entire family of Java APIs, including the JDBC API to access enterprise RDBMSs (e.g. Oracle, IBM DB2, MS SQL Server, MySQL, MS Access, SAP Adaptive Server Enterprise etc.).
11. Differentiate between Java Servlets and JavaServer Pages (JSP).
Answer: Java Servlets and JavaServer Pages (JSP) are complementary APIs, both offering a means for creating dynamic web content. A typical Servlet is actually a Java class implementing the javax.servlet.Servlet interface that runs within a web container or Servlet container, servicing client requests forwarded to it through the server. In HttpServlets, HTML tags are embedded within Java codes (generally within out.println statements), whereas in JSP pages, Java codes are embedded within HTML tags. So it is more suitable to write and modify JSP codes compared to Servlet codes. That is why unlike Servlets, which is a programmatic technology requiring significant developer expertise, JSP appeals to a much wider audience. Basically, JSP can provide all the functionalities of a Java Servlet in a more convenient way for the programmers.
Another advantage of JSP is the inherent separation of presentation from content facilitated by the technology, due its reliance upon reusable component technologies like the JavaBeans component architecture and Enterprise JavaBeans technology. By separating the look from the content we can put different people on different tasks: our web page design experts can build the HTML, leaving places for our Servlet programmers to insert the dynamic content. That’s why JSP is preferred over Servlets. Rather than choosing between Servlets and JavaServer Pages, we will find that most non-trivial applications will want to use a combination of JSP and Servlets. In fact, the JSP and Servlet are based around the concept of the web application, combining the two APIs into a unified framework.
12. Comment critically on this statement – ‘A JSP becomes a Servlet’.
Answer: A JSP file eventually becomes a full-fledged Servlet running in our web application. This looks like any other Servlet, except that the Servlet class is written for us by the web container. The container translates our JSP file (e.g. test.jsp) into a Servlet class source file (test_jsp.java), and then compiles it into a Java Servlet class (test_jsp.class). After that, the container loads the Servlet class, instantiates and initializes it as a Servlet object, makes a separate thread for each client request, and calls the Servlet’s service() method.
13. Mention the advantages of JSPs over Servlets.
Answer: JSPs have several advantages over Java Servlets:
- Separation of static content from dynamic content: With Servlets, the logic for generation of the dynamic content is an intrinsic part of the Servlet itself, and is closely tied to the static presentation templates responsible for the user interface (UI). Thus, even minor changes made to the UI typically result in the recompilation of the Servlet. This tight coupling of presentation and application logic part results in stiff, inflexible applications. However, with JSP, the logic to generate the dynamic content is kept separate from the static presentation templates by encapsulating it within external JavaBeans components. These are then created and used by the JSP page using special tags and scriptlets. When a page designer makes any changes to the presentation template, the JSP page is automatically recompiled and reloaded into the web server by the JSP engine.
- Write once run anywhere (WORA): JSP technology transports the concept of “Write once, run anywhere” to interactive web pages. JSP pages can be moved easily across platforms, and across web servers, without making any changes.
- Dynamic content can be presented in a variety of formats: There is nothing that mandates the static template data within a JSP page to be of a certain format. Consequently, JSP can service a diverse clientele ranging from conventional browsers using HTML, to mobile phones using WML, to other B2B applications using XML.
- Recommended web access layer for n-tier architecture: Oracle’s JEE Blueprints, which offers guidelines for building large-scale applications using the enterprise Java APIs, categorically recommends JSP over Servlets for serving dynamic content.
- Entirely extends the Servlet API: Being a Servlet developer, we don’t have to learn much for moving towards JSP. In fact, Servlet developers are at a distinct advantage because JSP is nothing but a high-level abstraction of Servlets. We can do almost anything that can be done with Servlets using JSP but more easily.
14. Mention different tags of a JSP program.
Answer: JSP uses several tags or scripting elements that performs various tasks such as declaring variables and methods, writing expressions, and calling other JSP pages. These are known as JSP scripting elements. The different types of scripting elements are summarized in the Table 8.2.
Table 1. JSP Tags
JSP Tag Type
Specifies translation time instructions to the JSP engine.
<%@ Directives %>
Declaration Declares and defines methods and variables.
<%! Java Declarations %>
Allows the developer to write free-form Java code in a JSP page.
<% Some Java code %>
Used as a shortcut to print values in the output HTML of a JSP page.
<%= An Expression %>
Provides request-time instructions to the JSP engine.
Used for documentation and for commenting out parts of JSP code.
<%– Any Text –%>
15. Explain the life cycle of JSP.
Answer: The graphical view of the JSP life cycle phase is as follows:
Figure 4: JSP life cycle phases
There are seven phases in JSP life cycle—
- JSP page translation: The JSP page is parsed and the corresponding Java Servlet code is created.
- Servlet compilation: The Java Servlet code is compiled.
- Load class: The compiled class is loaded.
- Build instance: An instance of the Servlet class is generated.
- Invoke jspInit(): This method is invoked before any other method to allow initialization.
- Invoke _jspService(): This method is invoked for each client request.
- Invoke jspDestroy(): This method is invoked when the web container decides to take the Servlet out of service.
16. Mention the implicit objects of JSP.
Answer: There are some object references in JSP which are created whenever they are used from inside the web page. These objects are automatically available for the JSP page author to use. These objects are called implicit objects and are summarized below in the Table 8.4.
Table 2. JSP Implicit Objects
Refers to the current request to the page
Used for sending a response to the client
Refers to the output stream for the page
Refers to the user’s session
Refers to web application’s environment
Refers to the Servlet’s configuration
Refers to the page’s environment
Refers to the page’s servlet instance
Used for error handling purposes
17. With the help of a diagram, explain how JSP works.
Answer: JSPs are built on top of Oracle’s Servlet technology. JSPs are essentially an HTML page with special JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather than .htm or .html. The JSP engine parses the .jsp and creates a Java Servlet source file. It then compiles the source file into a class file; this is done the first time and that is why the JSP is probably slower the first time it is accessed. Any time after this the special compiled Servlet is executed and is therefore returns faster.
Figure 5: JSP Architecture
Steps required for a JSP request:
- The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp). The web browser makes the request via the Internet.
- The JSP request gets sent to the Web server.
- The Web server recognizes that the file required is special (.jsp), therefore passes the JSP file to the JSP Servlet Engine.
- If the JSP file has been called the first time, the JSP file is parsed, otherwise go to step 7.
- The next step is to generate a special Servlet from the JSP file. The entire HTML required is converted to println statements.
- The Servlet source code is compiled into a class file.
- The Servlet is instantiated, calling the init and service methods.
- HTML from the Servlet output is sent via the Internet.
- HTML results are displayed on the user’s web browser.
18. What are the different types of JSP directives? Explain each with example.
Answer: Directives provide general information about the JSP page to the JSP engine. A directive tag always starts with <%@ and ends with %>.
There are 3 types of directives: page, include, and taglib.
The general syntax for the 3 directives is:
<%@ page attribute-list %>
<%@ include attribute-list %>
<%@ taglib attribute-list %>
In the above shown syntax, the attribute-list represents one or more attribute value-pairs that are specific to the directive. Some important points that are needed to be remembered about the syntax of the directive are as follows:
- The tag names, their attributes, and their values are all case sensitive.
- The value must be enclosed within a pair of single or double quotes.
- A pair of single quotes is equivalent to a pair of double quotes.
- There must be no space between the equals sign (=) and the value.
A page directive informs the JSP engine about the overall properties of a JSP page. For example, the following page directives inform the JSP engine that Java will be used as scripting language in our JSP page:
<%@ page language=”java” %>
An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc) into the current file. For example:
<%@ include file=”test.html” %> or <%@ include file=”test.jsp” %>
A taglib directive is used to associate a prefix with a tag library. For example:
<%@ taglib prefix=”test” uri=”taglib.tld” %>
19. Compare JSP with ASP.
Answer: JavaServer Pages (JSP) and Microsoft Active Server Pages (ASP) technologies have many similarities. They are listed below:
- Both are designed to create interactive pages as part of a web-based application.
- To a degree, both enable developers to separate programming logic from page design through the use of components that are called from the page itself.
- And both provide an alternative to creating CGI scripts that makes page development and deployment easier and faster.
But there are also a number of differences that exist:
JavaServer Pages (JSP)
Active Server Pages (ASP)
1) Web Server Support
Most popular web servers including Apache, Netscape, and Microsoft IIS can be easily enabled with JSP.
Native support only within Microsoft IIS or Personal Web Server. Support for select servers using third-party products.
2) Platform Support
Platform independent. Runs on all Java-enabled platforms.
Is fully supported under Windows. Deployment on other platforms is cumbersome due to reliance on the Win32-based component model.
3) Component Model
Relies on reusable, cross-platform components like JavaBeans, Enterprise JavaBeans, and custom tag libraries.
Uses the Win32-based COM component model.
Uses the Java code for scripting.
Supports VBScript and JScript for scripting.
Works with the Java security model.
Can work with the Windows NT security architecture.
6) Database Access
Uses JDBC for data access.
Uses Active Data Objects for data access.
20. What is JDBC?
Answer: Java applications cannot communicate directly with a RDBMS to submit data and retrieve the results of queries. This is because a RDBMS can interpret only SQL statements and not the Java language statements. So, we need some kind of mechanism to translate Java statements into SQL statements. In Java programming domain, the technology that enables database access and manipulation is called Java Database Connectivity (JDBC).
JDBC has two parts: the JDBC core API and the JDBC optional package API. The JDBC Core API is the main part of JDBC and it takes the form of the classes and interfaces in the java.sql package. The JDBC optional package API is specified in the javax.sql package and it supports connection pooling, distributed transactions, row sets, and so forth.
21. Describe the JDBC architecture in brief.
Answer: The JDBC architecture provides a mechanism to translate Java statements into SQL statements. The JDBC architecture can be categorized into two layers — (1) JDBC API Layer and (2) JDBC Driver API Layer. The description of JDBC architecture is given here. See Figure 10.1 below for detailed information.
Figure 6: JDBC Architecture
- JDBC API layer: It signifies a Java application that uses the JDBC API to interact with the JDBC drivers. A JDBC driver is software that a Java application uses to access a RDBMS. The Driver Manager of JDBC API connects the Java application to the driver.
- JDBC Driver API layer: It acts as an interface between a Java application and a RDBMS. This layer contains a driver, such as a MySQL driver or an Oracle driver, which enables connectivity to a database. A driver sends the request of a Java application to the database. After processing the request, the database sends the response back to the driver. The driver translates and sends the response to the JDBC API. The JDBC API forwards it to the Java application.
22. Discuss about different types of JDBC Drivers.
Answer: A JDBC driver can be fall into one of the 4 types: Type 1, Type 2, Type 3, and Type 4. The different types of JDBC drivers are given below—
- JDBC-ODBC Bridge driver [Type 1 Driver]
- Native-API Partly-Java driver [Type 2 Driver]
- Network Protocol Pure-Java driver [Type 3 Driver]
- Native Protocol Pure-Java driver [Type 4 Driver]
Each of the types is briefly discussed in the following segments.
- A JDBC-ODBC Bridge driver converts JDBC calls into ODBC calls that access the DBMS protocol. This data access method requires that the ODBC drivers be installed on the client machines.
- A Native-API Partly-Java driver converts JDBC calls into calls in the native DBMS protocol. Since this conversion takes place on the client side, some binary code must be installed on the client machine.
- A Network Protocol Pure-Java driver converts JDBC calls into a net protocol that is independent of any native DBMS protocol. Then, middleware software running on a server converts the net protocol to the native DBMS protocol. Since this conversion takes place on the server side, no installation is required on the client machine.
- A Native Protocol Pure-Java driver converts JDBC calls into a native DBMS protocol. Since this conversion takes place on the server side, no installation is required on the client machine.
23. What are the advantages of Servlets / JSPs over other technologies?
Answer: Servlets / JSPs have the following advantages over other technologies –
- Performance. The performance of Servlets is superior to CGI because there is no process creation for each client request. Instead, each request is handled by the Servlet container process. After a Servlet is finished processing a request, it stays resident in memory, waiting for another request.
- Portability. Similar to other Java technologies, Servlet applications are portable. We can move them to other operating systems without serious hassles.
- Rapid development cycle. As a Java technology, Servlets have access to the rich Java library, which helps speed up the development process.
- Robustness. Servlets are managed by the Java Virtual Machine. As such, we don’t need to worry about memory leak or garbage collection, which helps us write robust applications.
- Widespread acceptance. Java is a widely accepted technology. This means that numerous vendors work on Java-based technologies. One of the advantages of this widespread acceptance is that we can easily find and purchase components that suit our needs, which saves precious development time.
- Secure. Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.
- Extensibility. The Servlet API is designed in such a way that it can be easily extensible. As it stands today, the Servlet API supports HTTP Servlets, but in later date it can be extended for another type of Servlets.