Tuesday, September 25, 2012

Servlet Interview Questions - Part 2

As a continuation to the part 1 of questions on Servlets that we covered in this blog sometime ago, below are some more questions on Servlets. Hope you find them useful...

1. What are the new features added to Servlet 2.5?

Following are the new features introduced in Servlet 2.5:
• A new dependency on J2SE 5.0
• Support for annotations
• Loading the class
• Several web.xml conveniences
• A handful of removed restrictions
• Some edge case clarifications

2. What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:
i. Servlet class loading - For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
ii. Servlet instantiation - After loading, it instantiates one or more object instances of the servlet class to service the client requests.
iii. Initialization (call the init method) - After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
iv. Request handling (call the service method) - After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
v. Removal from service (call the destroy method) - A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

3. Why do we need a constructor in a servlet if we use the init method?

Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet).

Let us say in a plain java class, you created an init method that gets invoked under some condition, will you be able to invoke it without actually instantiating your class? That is why we need a constructor even for a Servlet.

4. When is the servlet loaded?

A servlet can be loaded when:
First request is made.
Server starts up (auto-load).
There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
Administrator manually loads.

5. When is a Servlet unloaded?

A servlet is unloaded when:
Server shuts down.
Administrator manually unloads.

6. What is the GenericServlet class?

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.

Note: This class is known as generic servlet, since it is not specific to any protocol whereas the HttpServlet is specific to the Http Protocol

7. Why is the HttpServlet class declared abstract?

The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. Just like any other abstract class, the HttpServlet is a partial skeleton which defines basic behavior and then gives the programmer the freedom to implement any of the other possible features he/she wants.

The simplest example here could be the fact that, any HttpServlet could handle multiple doXXX() methods as we call them which include doGet(), doPost() etc. So, in your applications, if you handle just the POST requests, then you need not implement a doGet() to override the default doGet() implementation.

8. Can a servlet have a constructor?

Sure Yes. Though we don’t explicitly call the constructor using the new() operator, the container internally invokes the Servlet class’ container when the servlet is initialized.

9. Should I override the service() method while using the HttpServlet?

We never override the service method, since the HTTP Servlets have already taken care of it. The default service function invokes the doXXX() method corresponding to the method of the HTTP request. For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

10. What are the differences between the ServletConfig interface and the ServletContext interface?

The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. There is only one ServletConfig parameter per servlet. The param-value pairs for ServletConfig object are specified in the < init-param > within the < servlet > tags in the web.xml file

A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container. There is one ServletContext for the entire webapp and all the servlets in a webapp share it. The param-value pairs for ServletContext object are specified in the < context-param > tags in the web.xml file.

11.What are the differences between forward() and sendRedirect() methods?

Some key differences between the two methods are:

a. A Forward is performed internally by the servlet whereas a redirect is a two-step process where the web application instructs the web browser to fetch a second/different URL
b. The browser and the user is completely unaware that a forward has taken place (The URL Remains intact) whereas in case of redirect, both the browser and the user will be made aware of the action including a change to the URL
c. The resource to which control is being forwarded has to be part of the same context as the one that is actually calling it whereas in case of redirect this is not a restriction.
d. Forwards are faster than redirects. Redirects are slower because it is actually handling two browser requests in place of forward’s one.

12. What are the difference between the include() and forward() methods?

The key differences between the two methods are:

a. The include() method inserts the contents of the specified resource directly into the flow of the servlet response, as if it were part of the calling servlet, whereas the forward() is used to show a different resource in place of the servlet that was originally called
b. The include() is often used to include common text or template markup that may be included in many servlets whereas forward() is often used where a servlet plays the role of a controller, processes some input and decides the outcome by returning a particular page response where control is transferred to a different resource

13. What is the use of the servlet wrapper classes?

The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behavior is to pass all method calls directly to the underlying objects.

14. What is a deployment descriptor?

A deployment descriptor is an XML document. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
The Java EE server reads the deployment descriptor at run time and acts upon the components accordingly.

15. What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root, whereas, the getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All path must start with a “/” and are interpreted as relative to current context root.

16. What is the < load-on-startup > element of the deployment descriptor?

The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. This setting by which a servlet is loaded even before it gets its first request is called pre-initialization of a servlet. It is also used to specify the order in which the files are to be loaded. The container will load the servlets in the order specified in this element.

17. What is servlet lazy loading?

Lazy servlet loading means – the container does not initialize the servlets as soon as it starts up. Instead it initializes servlets when they receive their first ever request. This is the standard or default behavior. If you want the container to load your servlet at start-up then use pre-initialization using the load-on-startup element in the deployment descriptor.

18. What is Servlet Chaining?

Servlet Chaining is a method where the output of one servlet is piped or passed onto a second servlet. The output of the second servlet could be passed on to a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

19. What are filters?

Filters are Java components that are used to intercept an incoming request to a Web resource or the response that is sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are:
Security checks
Modifying the request or response
Data compression
Logging and auditing
Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

20. What are the functions of the Servlet container?

The functions of the Servlet container are as follows:
a. Lifecycle management: It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
b. Communication support: It handles the communication between the servlet and the Web server.
c. Multithreading support: It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
d. Declarative security: It manages the security inside the XML deployment descriptor file.
e. JSP support: The container is responsible for converting JSPs to servlets and for maintaining them.

If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Servlets that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Saturday, September 15, 2012

Struts Interview Questions

The following are some common questions that you may encounter about the Struts Framework in Java/J2EE Technical Interviews. Struts is one of the most commonly used and popular frameworks that organizations use to develop large enterprise class applications. So, it is easily possible that when you are attending a job interview as a Java/J2EE Programmer/Lead, questions about the Struts Framework invariably pops up...

The following are some questions that can help you refresh your memory about the Struts Framework.

1. What is Struts framework?

Struts framework is an open-source framework use for developing the web applications in Java EE, based on the MVC-2 architecture. It uses and extends the Java Servlet API. Struts is a robust architecture and can be used for the development of applications of any size. Struts framework makes it much easier to design scalable and reliable Web applications with Java.

2. What design patterns are used in Struts?

Struts is based on model 2 MVC (Model-View-Controller) architecture.

Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern.

Struts also implement the following J2EE design patterns.
a. Service to Worker
b. Dispatcher View
c. Composite View (Struts Tiles)
d. Front Controller
e. View Helper
f. Synchronizer Token

An important point to note here is that, not all of these patterns may be used in every Struts based application and you may not require to remember all of these patterns. If you know that Struts is based on the MVC Framework, that is more than sufficient.

3. What is the MVC Framework?

MVC Stands for Model View Controller Framework

Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.

Model - The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

View - The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

Controller - The controller reacts to the user input. It creates and sets the model.

4. What are the components of a Struts based application?

Struts components can be categorize into Model, View and Controller:

Model - Components like business logic /business processes and data are the part of model.

View - HTML, JSP are the view components.

Controller - Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

5. What is the ActionServlet?

The ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request.

It serves as an Action factory – creating specific Action classes based on user’s request.

6. What is the role of an ActionServlet?

ActionServlet performs the role of Controller. It does the following:

a. Process user requests
b. Determine what the user is trying to achieve according to the request
c. Pull data from the model (if necessary) to be given to the appropriate view,
d. Select the proper view to respond to the user
e. Delegates most of this grunt work to Action classes
f. Is responsible for initialization and clean-up of resources

7. What is the ActionForm?

ActionForm is a javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

8. What are the important methods of ActionForm?

The important methods of ActionForm are : validate() & reset().

9. Describe the validate() and reset() methods of the ActionForm?

The validate() method is used to validate properties after they have been populated (In the JSP). It is called before FormBean is handed over to the Action. It returns a collection of ActionError objects as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

The reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set. Following is the method signature of the reset() method.

public void reset() {}

10. What is ActionMapping?

The Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is over.

For ex: You enter your credentials in the login page of your bank's internet banking website and then hit the "Login" button. How would the system know what to do next? It refers to the ActionMappings to find out what to do next based on the action chosen by the user.

11. How is the Action Mapping specified ?

We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from configuration element of struts-config.xml file

< action-mappings >
< action path="/submit" type="submit.SubmitAction" name="submitForm" input="/submit.jsp" scope="request" validate="true" >
< forward name="success" path="/success.jsp" / >
< forward name="failure" path="/error.jsp" / >
< / action >
< / action-mappings >

12. What is role of Action Class?

An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

Practically speaking, this class contains all the logic of what to do in response to the user action. Remember the login to banks website example I gave a couple of questions back, the system actually goes to the Action class corresponding to your action (Login) to try to figure out what needs to be done next.

13. In which method of Action class the business logic is executed ?

In the execute() method of Action class the business logic is executed. It performs the processing required to deal with this request, updates the server-side objects (Scope variables) that will be used to create the next page of the user interface and returns an appropriate ActionForward object

14. Can you give me a sample code for this execute method's Signature?

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;

15. Can we have more than one struts-config.xml file for a single Struts application?

A lot of people think that having multiple struts config files isnt possible for a single application but the truth is, it is very well possible. Unfortunately, in most real life scenarios, we would be using only one struts config file even though we can have many.

16. How would you configure your application to have multiple struts config files?

They can be configured as follows in your web.xml file:

< servlet >
< servlet-name > action < / servlet-name >
< servlet-class >
< / servlet-class >
< init-param >
< param-name > config < / param-name > < param-value > /WEB-INF/struts-config.xml, /WEB-INF/struts-admin.xml, /WEB-INF/struts-config-forms.xml < / param-value > < / init-param >
< servlet >

17. What is the difference between session scope and request scope when saving the formbean in struts?

When the scope is request,the values of formbean would be available for the current request. Whereas, when the scope is session, the values of formbean would be available throughout the session.

18. What are the different kinds of actions in Struts?

The different kinds of actions in Struts are:

19. What is DispatchAction?

The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

20. How will you use the DispatchAction?

To use the DispatchAction, follow these steps :
1. Create a class that extends DispatchAction (instead of Action)
2. In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
3. Do not override execute() method – Because DispatchAction class itself provides execute() method.
4. Add an entry to struts-config.xml

21. When would you use the ForwardAction?

The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

22. When would you use the IncludeAction?

The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

23. What is the difference between ForwardAction and IncludeAction?

The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.

24. What is LookupDispatchAction?

The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

25. When would you use LookupDispatchAction?

LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. This is typically useful when you create something that will be shared across different locales. For ex: The login page of an international banks website would look surprisingly similar in almost all countries. It does the same thing in all countries but what exactly happens after you finish the login depends on the country you are. So, this is the kind if scenario where LookupDispatchAction would come in handy.

26. What is difference between LookupDispatchAction and DispatchAction?

The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

27. What is SwitchAction?

The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application.

28. What if element has declaration with same name as global forward?

In this case the global forward is not used. Instead the element’s takes precendence.

29. What is DynaActionForm?

DynaActionForm is a specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean. Since the developer need not create actual bean java classes, a lot of developers prefer DynaActionForms.

30. What are the steps need to use DynaActionForm?

Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:

First in the struts-config.xml: change your to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm.


< form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >
< form-property name="userName" type="java.lang.String" / >
< form-property name="password" type="java.lang.String" / >
< / form-bean >

Second - In your Action subclass that uses your form bean:

1. import org.apache.struts.action.DynaActionForm
2. downcast the ActionForm parameter in execute() to a DynaActionForm
3. access the form fields with get(field) rather than getField()



public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(

31. How would you display validation errors on jsp page in a Struts Application?

tag displays all the errors. iterates over ActionErrors request attribute. Remember the ActionErrors that get created while using the validate() method? See Question No. 9 if you dont remember...

32. What are the various Struts tag libraries?

The various Struts tag libraries are:
1. HTML Tags
2. Bean Tags
3. Logic Tags
4. Template Tags
5. Nested Tags
6. Tiles Tags

33. What is the use of ?

repeats the nested body content of this tag over a specified collection.


< table border=1 >
< logic:iterate id="customer" name="customers" >
< tr >
< td > < bean:write name="customer" property="firstName" / > < / td >
< td > < bean:write name="customer" property="lastName" / > < / td >
< td > < bean:write name="customer" property="address" / > < / td>
< / tr >
< / logic:iterate >
< / table>

34. What are differences between < bean:message > and < bean:write >?

< bean:message >: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.

< bean:message key="prompt.customer.firstname" / >

< bean:write >: is used to retrieve and print the value of the bean property. < bean:write > has no body.

< bean:write name="customer" property="firstName" / >

35. How the exceptions are handled in struts?

Exceptions in Struts are handled in two ways:
1. Programmatic exception handling - Using explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.

2. Declarative exception handling - You can either define handling tags in your struts-config.xml or define the exception handling tags within tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.

36. Can you give an example of Programmatic Exception Handling?

< global-exceptions >
< exception key="some.key" type="java.lang.NullPointerException" path="/WEB-INF/errors/null.jsp" / >
< / global-exceptions >

37. Can you give an example of declarative exception handling?

< exception key="some.key" type="package.SomeException" path="/WEB-INF/somepage.jsp" / >

38. What are some benefits of using DynaActionForm?

The biggest advantage is that - we need not create multiple classes to hold form information. We can just declare forms as and when required inside the struts-config.xml file and we are good to go.

39. Can you think of any drawbacks of the DynaActionForm?

Of Course. Every coin has two sides. Some drawbacks of using DynaActionForm could be:

1. The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger and the config file in itself could become unmanageable
2. The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
3. ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

40. How can we make message resources definitions file available to the Struts framework environment?

We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to struts-config.xml.

< message-resources parameter="com.login.struts.ApplicationResources" / >

If you want to add more questions to this list or if you wish to have any question answered, leave a comment in this page or drop a note to anandvijayakumar007@gmail.com

Monday, July 2, 2012

Java Database Connectivity JDBC Interview Questions Part 2

As the article on JDBC Interview Questions part 1 was becoming too long, I stopped with 25 questions. So, now in this article, we are going to look at some more questions on the topic of Java Database Connectivity.

Before we proceed, you can re-visit the article titled Java Database Connectivity - JDBC if you want to refresh your memory on JDBC concepts.

Questions – Part 2:

1. How will you retreive database warnings from a Connection object in JDBC?

//Retrieving warning from connection object
SQLWarning warning = conn.getWarnings();

//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();

2. How will you retreive database warnings from a Statement object in JDBC?

//Retrieving warning from statement object

//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();

3. How will you retreive database warnings from a ResultSet object in JDBC?

//Retrieving warning from resultset object

//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();

4. What does the clearWarnings() method do?

A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object.

5. What happens when I try to call the getWarning() method on a connection/statement/resultset after it has been closed?

Trying to call the getWarning() method on either of these 3 objects after they are closed will cause an SQLException to be thrown.

6. Let us say that I just closed my Statement object so, I cannot access the getWarning() on my statement. Can I still access the getWarning() on my ResultSet?

No. Closing a Statement automatically closes the ResultSet connected to it. So, you will get the same SQLException if you try to do so.

7. What is DatabaseMetaData?

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology ("JDBC driver") that is used with it. Use DatabaseMetaData to find information about your database, such as its capabilities and structure.

8. How will you use the DatabaseMetaData? Can you write a sample example code?

DatabaseMetaData md = conn.getMetaData();
System.out.println("Database Name: " + md.getDatabaseProductName());
System.out.println("Database Version: " + md.getDatabaseProductVersion());
System.out.println("Driver Name: " + md.getDriverName());
System.out.println("Driver Version: " + md.getDriverVersion());

9. What is ResultSetMetaData?

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns.

10. How will you use the ResultSetMetaData? Can you write a sample example code?

ResultSet rs = stmt.executeQuery("SELECT * FROM TABLE_NAME");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);

11. What is rowset?

A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet.

12. Why do we need a RowSet?

RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet

13. What are the advantages of using RowSet over ResultSet?

There are two clear advantages of using RowSet over ResultSet:

* RowSet makes it possible to use the ResultSet object as a JavaBeans component.
* RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

14. What are the different types of RowSet ?
There are two types of RowSet are there. They are:
* Connected - A connected RowSet object connects to the database once and remains connected until the application terminates.
* Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

15. Can you give an example of Connected RowSet?

A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver.

16. Can you give an example of Disconnected RowSet?

A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).

17. What are the benefits of having JdbcRowSet implementation?

The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet
* This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time.
* It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object.

18. What is the need of BatchUpdates feature in JDBC?

The BatchUpdates feature allows us to group SQL statements together and send to database server in one single shot instead of multiple calls.

19. What is a DataSource?

A DataSource object is the representation of a source of data in the Java programming language.

In basic terms:
* A DataSource is a facility for storing data.
* DataSource can be referenced by JNDI.
* Data Source may point to RDBMS, file System , any DBMS etc..

Typically in enterprise application perspective, the term DataSource can be used interchangeably with a RDBMS database because in almost all cases, our DataSource will be pointing to an RDBMS database.

20. What are the advantages of DataSource?

The few advantages of using data source are :
* An application does not need to hardcode driver information, as it does with the DriverManager.
* The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details.
* The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.

21. What is the difference between a Statement and a PreparedStatement?

Some of the main differences between a statement & PreparedStatement are:

Statement PreparedStatment
A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database. A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
Statement has to verify its metadata against the database every time. A prepared statement has to verify its metadata against the database only once.
If you want to execute the SQL statement once go for STATEMENT If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries.
22. What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE in ResultSets?

Some of the main differences between a TYPE_SCROLL_INSENSITIVE & TYPE_SCROLL_SENSITIVE are:

An insensitive resultset is like the snapshot of the data in the database when query was executed. A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive. After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Performance not effected with insensitive. Since a trip is made for every ‘get’ operation, the performance drastically get affected.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on JDBC that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.

JDBC Interview Questions - Part 1

Java/J2EE Interview Questions - Home Page

Java Database Connectivity JDBC Interview Questions Part 1

I had posted an article titled “Java Database Connectivity - JDBC” last week on Friday and was planning to post the article on JDBC Interview questions today. But, before I could do so, one of our blog readers pointed out the fact that I haven’t posted it yet but have referenced it already…

Well, here we go. The following are some questions that you may encounter on JDBC concepts during your interviews. Remember that if you are a junior level developer (with less than 3 years working experience) many of these questions may seem too complicated for you and frankly you won’t be expected to know them either.

You cannot think of an Enterprise Java Application that does not connect to a database. So, a strong understanding of JDBC concepts is crucial to your success as a potential candidate during an interview.

Questions – Part 1:

1. What is the JDBC?

Java Database Connectivity (JDBC) is a standard Java API that is used to interact with relational databases from within a Java application. JDBC has set of classes and interfaces which can use from our Java application and interact with the database.

2. What are the Basic Steps in writing a Java program to connect to a database using JDBC?

The basic steps in connecting to a database using JDBC are:

1. Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded).
2. Open the connection to database which is then used to send SQL statements and get results back.
3. Create JDBC Statement object. This object contains SQL query.
4. Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
5. Process the result set.
6. Close the connection.

3. What are the main components of JDBC ?

The five main components of JDBC are:

1. Driver Manager
2. Driver
3. Connection
4. Statement &
5. ResultSet

4. How does a JDBC application work?

A JDBC application can be logically divided into two layers:
1. Driver layer
2. Application layer

First the Driver layer consists of DriverManager class and the available JDBC drivers. The application begins with requesting the DriverManager for the connection. An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer. The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results.

5. How do I load a database driver with JDBC 4.0 / Java 6?

Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.

Remember - if the correct JAR Files are missing in the classpath, this auto feature will not work

6. What is JDBC Driver interface?

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver so that the Java classes that connect to the database can use them.

7. What does the connection object represents?

The connection object represents a literal connection or a communication context through which our Java code can interact with a database. i.e., all communication with database is through connection object only.

8. What is a Statement?

The Statement acts like a vehicle through which SQL commands can be sent. You can create a Statement as follows:

Statement stmt = conn.createStatement();

This method returns an object which implements statement interface which can be executed.

9. What is a PreparedStatement?

A prepared statement is an SQL statement that is precompiled by the database. It is a sub-set of the Statement. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.

You can create a prepared statement as follows:

PreparedStatement pstmt = conn.prepareStatement("UPDATE Emp_Salary SET Salary = ? WHERE Emp_Id = ?");
pstmt.setBigDecimal(1, 75000.00);
pstmt.setInt(2, 12345);

Note that conn is an instance of the collection class and the "?" represent the parameters that are to be passed to the query/prepared statement before it can be executed.

10. What are callable statements?

Callable statements are used from JDBC application to invoke stored procedures and functions objects of a database.

11. Can you call a stored procedure using JDBC? If so, how?

Yes, you can call Stored Procedures using JDBC. we have to use the CallableStatement to do so.


CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");

Here conn is an instance of the Connection class.

12. How many types of JDBC drivers are there and What are they?

There are four types of drivers defined by JDBC as follows:
1. Type 1 – JDBC-ODBC Bridge
2. Type 2 – Native API (Partly Java) Driver
3. Type 3 – Net-Protocol Fully Java Driver
4. Type 4 – Pure Java Driver

Type 4 JDBC driver is most preferred kind of approach in JDBC.

13. Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.

14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

15. What are the standard transaction isolation levels defined by JDBC?

The values are defined in the class java.sql.Connection and are:


You need to double check that the database you are connecting to, supports these isolation levelts.

16. What is a ResultSet?

The ResultSet represents set of rows retrieved due to query execution. You get a result set object as the output when you execute a query using the Statement or the PreparedStatement objects.

ResultSet rs = stmt.executeQuery(sqlQuery);

17. What are the types of resultsets?

JDBC supports 3 types of ResultSets. They are:


18. What are the types of statements in JDBC?

The JDBC API has 3 types of Statement Interfaces. They are:

1. Statement
2. PreparedStatement
3. CallableStatement

19. What are the differences/key features between the 3 different types of Statements in JDBC?

* This interface is used for executing a static SQL statement and returning the results it produces.
* The object of Statement class can be created using Connection.createStatement() method.

* A SQL statement is pre-compiled and stored in a PreparedStatement object.
* This object can then be used to efficiently execute this statement multiple times.
* The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface.

* This interface is used to execute SQL stored procedures.
* This extends PreparedStatement interface.
* The object of CallableStatement class can be created using Connection.prepareCall() method.

20. What is Connection pooling? What are the advantages of using a connection pool?

Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database. Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool. Apart from performance this also saves you resources as there may be limited database connections available for your application.

21. What does the Class.forName() method do?

Method forName() is a static method of java.lang.Class. This can be used to dynamically load a class at run-time. Class.forName() loads the class if its not already loaded. It also executes the static block of loaded class. Then this method returns an instance of the loaded class. So a call to Class.forName('MyClass') is going to do following
- Load the class MyClass.
- Execute any static block code of MyClass.
- Return an instance of MyClass.

JDBC Driver loading using Class.forName is a good example of best use of this method. The driver loading is done like this


All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. A MySQL JDBC Driver has a static initializer which looks like this:

static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");

Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager.

22. When to use a PreparedStatement and when to use a Statement?

Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

There are few advantages of using PreparedStatements over Statements
* Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster.
* In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way.
* SQL injection attacks on a system are virtually impossible while using PreparedStatements.

23. What do you mean by the term pre-compiled from a PreparedStatemnet perspective?

The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution which makes it much faster than executing a fresh query that has to be compiled before execution.

24. What does setAutoCommit(false) do?

A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode manually as follows:


Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method as follows:


Alternately, if you want to ensure that all further transactions/queries are auto-committed then you can enable auto-commit as follows:


25. What are database warnings and How can I get them?

Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects.

The call to the getWarnings() method of either of these objects retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously.

JDBC Interview Questions - Part 2

Java/J2EE Interview Questions - Home Page

Friday, June 29, 2012

Java Database Connectivity - JDBC

JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems. The purpose of this article is to give you an introductory overview of this JDBC concept. Before we go any further, let me reiterate that JDBC in itself is a very large topic and what you see in this chapter is just a drop in the ocean. But, this should be sufficient to get you started into using JDBC in your day to day programs.

What is Java Database Connectivity or JDBC?

The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.

Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.

Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.

In short JDBC helps the programmers to write java applications that manage these three programming activities:

1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database
Why is Java Database Connectivity Important?

Java, as you might be aware is a very powerful programming language which is widely used to create enterprise class applications. Any enterprise application that you may use has to display and manipulate data in some form and this data is invariably stored in some Relational Database (RDBMS) like Oracle, Sybase etc. So, the system or the application per say must connect and interact with the database in order to display the required information on screen. This is exactly where the JDBC layer fits in.

Without JDBC, there is no way that the application can effectively interact with a Relational Database like Oracle or Sybase and perform its functions. The latest version of the JDBC API is 4.0. Some of the new Features Added to JDBC 4.0 are:

1. Auto-loading of JDBC driver class
2. Connection management enhancements
3. Support for RowId SQL type
4. DataSet implementation of SQL using Annotations
5. SQL exception handling enhancements
6. SQL XML support

JDBC Architecture:

At a high level, the JDBC Architecture consists of two layers:

1. The JDBC API, which provides the application-to-JDBC Manager connection.
2. The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to different databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the Java application is shown below:

Main Components of JDBC:

There are numerous components that work together as part of the JDBC API in order to allow an enterprise java application to connect to a database. However, the following are the main components:
1. DriverManager - Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub-protocol. The first driver that recognizes a certain sub-protocol under JDBC will be used to establish a database Connection.
2. Driver - The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly every time.
3. Connection - Interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database happens through the connection object only.
4. Statement - Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
5. ResultSet - The ResultSet represents set of rows retrieved due to query execution which gets returned to the calling system.

A Sample Code to connect to a database using JDBC:

The following is a code snippet that you can use to connect to an Oracle database using a thin driver. The steps in connecting to a database and obtaining the output are:
1. Load the Driver Class
2. Create a Connection
3. Create a Statement
4. Execute the query and obtain the ResultSet
5. Access the output of the query from the ResultSet

Each line of code that represents each of the above steps is marked by the comment followed by a number.

import java.sql.*;
public class InheringJavaJDBCTest {
public static void main (String args []) throws Exception

Class.forName ("oracle.jdbc.driver.OracleDriver"); //1

Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@hostname:1526:testdb", "scott", "tiger"); //2

Statement stmt = conn.createStatement(); //3
ResultSet rs = stmt.executeQuery("select 'Hi' from dual"); //4
while (rs.next())
System.out.println (rs.getString(1)); // 5

JDBC Driver Categories/Types:

If you saw the above code example correctly, we have loaded a driver class as the first step before we established the database connection. JDBC has 4 different categories and all drivers will invariably fit into either of these 4 categories. The four JDBC driver categories are:

1. Type 1 – JDBC-ODBC Bridge
2. Type 2 – Native API (Partly Java) Driver
3. Type 3 – Net-Protocol Fully Java Driver
4. Type 4 – Pure Java Driver

Type 1: JDBC/ODBC Bridge requires an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important.

Type2: Native API (partly-Java driver) type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection. A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

Type 3: A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products. This type of driver can access any database.

Type 4: Proprietary Protocol-Net (pure Java driver) has the same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client. A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.

Types of Statements you can use in a Java Program:

As you may have seen in the code example section, a Statement is used to pass or rather send the SQL Query that we wish to execute to the database. In our example we saw a simple “Statement”. The JDBC API has 3 types of statements that you can use in your Java Programs. They are:
1. Statement
2. PreparedStatement &
3. CallableStatement

Each of these types of statements has a different purpose and has to be used differently. Both Statement & PreparedStatement are used to execute basic SQL Queries while the CallableStatement is used to execute or invoke Stored Procedures.

A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database. The Statement has to verify its metadata against the database every time. If you want to execute the SQL statement once go for STATEMENT.

A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first. If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries.

A CallableStatement extends the PreparedStatement Interface. It can be used to call Stored Procedures from java code.

Types of Result Sets you can use in a Java Program:

As you may have seen in the code example section, a ResultSet is the output that we will get once our query is executed. Typically, we will iterate through the result set and obtain all the values that are returned as the output of execution of the Statement. The JDBC API gives us an option to use 3 different types of Result Sets and this value can be defined while establishing the Connection. They are:

1. TYPE_FORWARD_ONLY - specifies that a resultset is not scrollable, that is, rows within it can be advanced only in the forward direction.
2. TYPE_SCROLL_INSENSITIVE - specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.
3. TYPE_SCROLL_SENSITIVE - specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.

The TYPE_FORWARD_ONLY resultset is the default type of resultset that will get created and it is always insensitive.

I hope this chapter gave you a basic overview of the JDBC concepts. As I had said at the beginning of the chapter, JDBC is an ocean and we haven’t even scratched the surface of that vast topic. If you have any specific questions related to JDBC, visit the article on “JDBC Interview Questions” to see if it has already been answered. If you can’t find an answer to your question, either leave a comment in this page or on the “JDBC Interview Questions” page and I will try to answer them.

JDBC Interview Questions - Part 1

JDBC Interview Questions - Part 2

Java Collections Interview Questions - Part 2

As a continuation from the part 1 of questions on the Java Collections topic, this article is going to contain some more questions on the Java Collections area. If you want to visit the part 1 questions click here

Apart from the questions in the Part 1 and below, there are a few articles that I have put up (as part of the SCJP Certification series) on Collections that you might find useful. You can use them to revise/review your understanding of Java collections.

They are:

Introduction to Collections
ArrayList Basics
Sorting Collections
Searching Collections
Collections Summary


1. What is the difference between java.util.Iterator and java.util.ListIterator?

Iterator - Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements
ListIterator - extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

2. What is the difference between the HashMap and a Map?

Map is an Interface which is part of Java collections framework. It stores data as key-value pairs.
Hashmap is class that implements that using hashing technique.

3. What does synchronized means in Hashtable context?

Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
This adds an overhead which makes the Hashtable slower when compared to the Hashmap. You must choose a Hashmap when you want faster performance and choose the Hashtable when you want thread safety

4. Can we make a Hashmap thread safe? If so, how?

HashMap can be made thread safe by synchronizing it. Example:
Map m = Collections.synchronizedMap(hashMap);

5. Why should I always use ArrayList over Vector?
You should choose an ArrayList over a Vector because – not all systems are multi-threaded and thread safety is not a mandatory requirement. In such cases, using a Vector is not only overkill but also adds a lot of overhead which might slow down system performance. Even if you are just iterating through a vector to display its contents, the lock on it still needs to be obtained which makes it much slower. So, choose the ArrayList over a Vector unless your system is multi-threaded.

6. What is an enumeration?

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

7. What is the difference between Enumeration and Iterator?

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only.

8. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort()? Which one is faster? Which one to use and when?

Actually speaking, the underlying sorting algorithm & mechanism is the same in both cases. The only difference is type of input passed to them. Collections.sort() has a input as List so it does a conversion of the List to an array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have an array available with you and you want to sort it.

9. What is java.util.concurrent BlockingQueue? How it can be used?

The BlockingQueue is available since Java 1.5. Blocking Queue interface extends collection interface, which provides you the power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.

10. What is the ArrayBlockingQueue?

An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic "bounded buffer" (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.

11. Why doesn't Map interface extend Collection?

Though the Map interface is part of collections framework, it does not extend collection interface. This was done as a design decision by Sun when the Collection framework was created. Think of it this way – A Map contains key-value pair data while a general collection contains only a bunch of values. If the map were to extend the collection class, what will we do with the keys and how will we link the values to their corresponding keys? Alternately, if the collection were to extend the Map, then, where will we go to get the key information for all the values that are already in the Collection?

Get the idea? For all practically purposes a Map is considered a collection because it contains a bunch of data in key-value pairs but it does not explicitly extend the collection interface.

12. Which implementation of the List interface (ArrayList or LinkedList) provides for the fastest insertion of a new element into the list?


If you are surprised about the answer you see above, read the question again “Fastest Insertion of a new element into the list”. The question is about inserts and not reading data. So, the linkedlist is faster. Because, when an element is inserted into the middle of the list in an ArrayList, the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

13. Which implementation of the List Interface (ArrayList or LinkedList) provides for faster reads during random access of data?

ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list.

14. Which implementation of the List Interface (ArrayList or LinkedList) uses more memory space for the same amount (number) of data?

Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers. So, the LinkedList uses more memory space when compared to an ArrayList of the same size

15. Where will you use ArrayList and Where will you use LinkedList?

If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time (depending on the location of the object being added/removed) in an ArrayList.

If the purpose of your collection is to populate it once and read it multiple times from random locations in the list, then the ArrayList would be faster and a better choice because Positional access requires linear-time (depending on the location of the object being accessed) in a LinkedList and constant-time in an ArrayList.

In short - If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.

16.Why insertion and deletion in ArrayList is slow compared to LinkedList?

ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.

During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

17.How do you traverse through a collection using its Iterator?

To use an iterator to traverse through the contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s iterator() method.
2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
3. Within the loop, obtain each element by calling next().

18.How do you remove elements during Iteration?

Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.

19.What are the main implementations of the List interface?

The main implementations of the List interface are as follows :
ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).

20.What are the advantages of ArrayList over arrays?

Some of the advantages ArrayList has over arrays are:
It can grow dynamically
It provides more powerful insertion and search mechanisms than arrays.

21.How to obtain Array from an ArrayList?

Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList();

Object a[] = arrayList.toArray();

22.Why are Iterators returned by ArrayList called Fail Fast?

Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. So, it is considered fail fast.

23.How do you sort an ArrayList (or any list) of user-defined objects?

Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

24.What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable
where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:

int i = object1.compareTo(object2)

If object1 < object2: The value of i returned will be negative.

If object1 > object2: The value of i returned will be positive.

If object1 = object2: The value of i returned will be zero.

25.What are the differences between the Comparable and Comparator interfaces?

The Comparable uses the compareTo() method while the Comparator uses the compare() method
You need to modify the class whose instance is going to be sorted and add code corresponding to the Comparable implementation. Whereas, for the Comparator, you can have a separate class that has the sort logic/code.
In case of Comparable, Only one sort sequence can be created while Comparator can have multiple sort sequences.

If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Collections that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list

Java Collections Interview Questions - Part 1 - Click Here

More Java & J2EE Interview Questions with Answers - Click Here

Wednesday, January 25, 2012

Creating Listeners Containing a Single Method Call

Java SE 1.4 introduces a mechanism that lets you specify simple event listeners without programming inner classes. (I am one of those people who doesn't like to use inner classes much, so I take any opportunity that is available to avoid using them) For example, suppose you have a button labeled “Load” whose event handler contains a single method call:

Of course, you can always use an anonymous inner class:

loadButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)

But the EventHandler class can create such a listener automatically, with the call
EventHandler.create(ActionListener.class, frame, "loadData")

Of course, you still need to install the handler:
loadButton.addActionListener(EventHandler.create(ActionListener.class, frame, "loadData"));

If the listener calls a method with a single parameter that can be obtained from the event parameter, you can use another form of the create method. For example
EventHandler.create(ActionListener.class, frame, "loadData", "source.text")

is equivalent to

new ActionListener()
public void actionPerformed(ActionEvent event)
frame.loadData(((JTextField) event.getSource()).getText());

The property names source and text turn into method calls getSource and getText.

A Working Example:

Let us understand the usage of these single method calls better with a simple example.
As you might have figured out by now, Swing programs use the Metal look and feel by default (We haven’t set any look and feel till now in our Swing programs, or have we?) There are two ways to change to a different look and feel. The first way is to supply a file swing.properties in the jre/lib subdirectory of your Java installation. In that file, set the property swing.defaultlaf to the class name of the look and feel that you want. For example:

Note that the Metal look and feel is located in the javax.swing package. The other look-and-feel packages are located in the com.sun.java package and need not be present in every Java implementation. Currently, for copyright reasons, the Windows and Macintosh look-and-feel packages are only shipped with the Windows and Macintosh versions of the Java runtime environment.
The second way is to change the look and feel dynamically. Call the static UIManager.setLookAndFeel method and give it the name of the look-and-feel class that you want. Then call the static method SwingUtilities.updateComponentTreeUI to refresh the entire set of components. You need to supply one component to that method; it will find all others. The UIManager.setLookAndFeel method may throw a number of exceptions when it can’t find the look and feel that you request, or when there is an error loading it. Worrying about those exceptions is currently out of our scope and we will deal with them later.

Here is an example showing how you can switch to the Motif look and feel in your program:

String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
catch(Exception e) { e.printStackTrace(); }

To list down all installed look and feel implementations, call

UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();

Then you can get the name and class name for each look and feel as below:
String name = infos[i].getName();
String className = infos[i].getClassName();

Lets now look at the code for a class that will dynamically change the look and feel of our screen. Our code will identify the available look and feel based on the code snippet above and create buttons dynamically mentioning them. When we click on each of the buttons, the look and feel of the frame and the components inside it will change dynamically.


import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;

* @version 1.1 02-June-2011
* @author Anand Vijayakumar
public class TestLookNFeel
public static void main(String[] args)
EventQueue.invokeLater(new Runnable()
public void run()
LookNFeelFrame frame = new LookNFeelFrame();

* A frame with a button panel for changing look and feel
class LookNFeelFrame extends JFrame
public LookNFeelFrame()
setTitle("Look N Feel Test");

buttonPanel = new JPanel();

UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo info : infos)
makeButton(info.getName(), info.getClassName());


* Makes a button to change the look and feel.
void makeButton(String name, final String plafName)
// add button to panel

JButton button = new JButton(name);

// set button action

button.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)
// button action: switch to the new look and feel
catch (Exception e)

private JPanel buttonPanel;

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;

If you run this code, you may get a different number of buttons in your computer. I got 4 in mine and the output if I click on each is as follows:

Previous: Basics of Event Handling

Monday, January 9, 2012

Chapter 13: Nested Locks

Imagine a scenario where a synchronized method is calling a non-synchronized method of the same object. In such a situation, the new method has no reason to obtain the lock because; the method calling it already owns the lock.

The reason this works is that Java does not blindly grab the lock when it enters synchronized code. If the current thread owns the lock, there is no reason to wait for the lock to be freed or even to grab the lock. Instead, the code in the synchronized section just executes. Furthermore, the system is smart enough to not free the lock if it did not initially grab it upon entering the synchronized section of code. This works because the system keeps track of the number of recursive acquisitions of the lock, finally freeing the lock upon exiting the first method (or block) that acquired the lock. This functionality is called nested locking.

Yet, it will be a good idea to synchronize methods like this. Are you tempted to ask “Why?”

If you were, think of this scenario. Let’s say another developer makes some new code changes without knowing that this code needs to have the object lock. So, if this developer makes some changes that might affect the way the thread executes or how the locks are acquired, then your code will be messed up big time. That is why I said, it would be a good idea to synchronize those methods as well.

Nested locks are also supported by the ReentrantLock class; the class that implements the Lock interface that we used in the previous chapters. If a lock request is made by the thread that currently owns the lock, the ReentrantLock object just increments an internal count of the number of nested lock requests. Calls to the unlock() method decrement the count. The lock is not freed until the lock count reaches zero. This implementation allows these locks to behave exactly like the synchronized keyword. Note, however, that this is a specific property of the ReentrantLock class and not a general property of classes that implement the Lock interface.

The ReentrantLock classlooks like below:
public class ReentrantLock implements Lock {
public int getHoldCount( );
public boolean isLocked( );
public boolean isHeldByCurrentThread( );
public int getQueueLength( );

The getHoldCount() method returns the number of acquisitions that the current thread has made on the lock. A return value of zero means that the current thread does not own the lock: it does not mean that the lock is free. To determine if the lock is free; not acquired by any thread; the isLocked() method may be used.

Two other methods of the ReentrantLock class are also important to this discussion. The isHeldByCurrentThread() method is used to determine if the thread is owned by the current thread, and the getQueueLength() method can be used to get an estimate of the number of threads waiting to acquire the lock. This value that is returned is only an estimate due to the race condition that exists between the time that the value is calculated and the time that the value is used after it has been returned.

Previous: Choosing a Locking Mechanism
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.


Google+ Followers