opencodez

101 Most Important Frequently Asked Advance Java Interview Questions – Part 1

In this article, we are going to list down 101 Most Important and Frequently Asked Advanced Java Interview Questions that will give you enough exposure and confidence to ace at Job Interview.

Java is on evolution spree. The new versions of Java are being released even before you get to know the last version. With all this, the core of java remains same and with it, one needs to be proficient at it.  We will split the questions into two parts.

Read second part – 101 Most Important Frequently Asked Advance Java Interview Questions x Part 2

Q.1: What is JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage.

Q.2: Which are the Common JDBC Components?

The JDBC API provides the following interfaces and classes −

DriverManager: This class 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 subprotocol under JDBC will be used to establish a database Connection.

Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.

Connection: This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.

Statement: You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures.

ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.

SQLException: This class handles any errors that occur in a database application.

Q.3: What is JDBC Driver?

JDBC Driver is a software component that enables java application to interact with the database.

JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server.

For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK, contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in their database driver.

JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4.

 Q.4: Which are the different JDBC drivers?

Type 1: JDBC-ODBC Bridge Driver:

Type 2: JDBC-Native API

Type 3: JDBC-Net pure Java

Type 4: 100% Pure Java

Q.5: Which are the different Steps to connect to the database in java?

  1. Load driver
  2. Create connection
  3. Create statement
  4. Execute queries
  5. Process the result
  6. Close Connection

Code Snippet:

import java.sql.*;
import java.io.*;
class JDBCDemo 
{
	public static void main(String[] args) throws SQLException 
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
	try
	{
		Class.forName("org.postgresql.Driver");
		conn =DriverManager.getConnection("jdbc:postgresql://localhost/employeeDB","student",“1234");
			if(conn==null)
				System.out.println("Connection failed ");
			else
			{
				System.out.println(“Connection successful..”);
				stmt = conn.createStatement();
				rs = stmt.executeQuery("Select * from emp");
					while(rs.next())
					{
						System.out.print("ID = " + rs.getInt(1));
						System.out.println("Name = " + rs.getString(2));
						System.out.println("Salary = " + rs.getInt(3));
					}
				conn.close();
			}
}
catch(Exception e)    { System.out.println(e);	}
}
}// end of class 

Q.6: In JDBC What is The DriverManager class?

The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver.

The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().

Example:

Connection con=DriverManager.getConnection(  "jdbc:postgresql://localhost/mydb”,“test user","password");

Q.7: What is JDBC Statement?

JDBC API Statement is used to execute SQL queries in the database.

You need to create one using the Connection objectxs createStatement( ) method, as in the following example −

Statement stmt = null;
stmt = conn.createStatement( );

This Statement is used to execute static SQL queries by passing query through different execute methods like execute(), executeQuery(), executeUpdate() etc.

rs = stmt.executeQuery("Select * from emp");

Q.8: What is the purpose Class.forName method?

This method is used to load the driver that will establish a connection to the database.

Example: to establish a connection with postgres database              

Class.forName("org.postgresql.Driver");

Q.9: What are the types of statements in JDBC?

There are 3 types of statements in JDBC

1. Statement – used for the general purpose access to a database. Useful when we are using static SQL statement at runtime and it can’t accept parameters.

Statement stmt = null;

stmt = conn.createStatement( );

2. PreparedStatement − Useful when we want to execute SQL statement repeatedly.  Input data is dynamic and it accepts input at run time.

PreparedStatement  pstmt = null;
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);

3. CallableStatement − to call stored procedures on the database.

CallableStatement cstmt = null;
cstmt = conn.prepareCall (SQL);

Q.10: Which type of JDBC driver is the fastest one?

Type 4 driver is the fastest one, it is a pure Java-based driver communicates directly with the vendorxs database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.

This kind of driver is extremely flexible, you donxt need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Q.11: How can we execute stored procedures?

Stored procedures can be executed using callable statement.

Example:

Connection con = null;
CallableStatement callSt = con.prepareCall("{call myStorepro(?, ?)}");
callSt.setString(1, "java");

Q.12: What is a ResultSet?

By using The ResultSet set of rows retrieved after query execution.

Resultset objects hold data retrieved from a database after SQL query execution using Statement objects. It acts as an iterator to allow you to move through its data.

Statement stmt = null;

ResultSet rs = null;

stmt = conn.createStatement();

rs = stmt.executeQuery("Select * from emp");

while(rs.next())

{

System.out.print("ID = " + rs.getInt(1));         //print the data from first column

System.out.println("Name = " + rs.getString(2));  // from second column

System.out.println("Salary = " + rs.getInt(3));   //from third column

}

Q.13: How you can view result set?

There is a getXXX() method for each of the possible data types, and each get method has two versions −(XXX is a type of example)

For example, if the column you are interested in viewing contains an int, you need to use one of the getInt() methods of ResultSet .

Q.14: Explain Scrollable Result SET.


Scrollable ResultSet:

  1. Statement createStatement(int rs_type, int rs_concur)
  2. .PreparedStatement creation method for Scrollable ResultSet

PreparedStatement prepareStatement(String sql, int rs_type, int rs_concur)

  1. CallableStatement creation method for Scrollable ResultSet

CallableStatement prepareCall(String sql, int rs_type, int rs_concur)

The rs_type can be any of the following values:
ResultSet.TYPE_FORWARD_ONLY

ResultSet.TYPE_SCROLL_SENSITIVE

ResultSet.TYPE_SCROLL_INSENSITIVE

⇒ The first one is the default in case of not specifying the ResultSet type explicitly.

⇒ The later two are used for scrolling within the rows.

⇒ The rs_concur can be any of the following two values:

ResultSet.CONCUR_READ_ONLY

ResultSet.CONCUR_UPDATABLE

Q.15: Which are the methods of Scrollable ResultSet?

Following methods to move the row pointer:

1. first() – Move the pointer to first row.

2. last() – Move the pointer to last row.

3. next() – Move the pointer to next row from current position.

4. previous() – Move the pointer to previous row from the current position.

5. absolute(int index) – Move the pointer to the row at given index (index starts with -1)

6. relative(-1)

Q.16:What is Updatable ResultSet?

ResultSet.CONCUR_UPDATABLE while creating the Statement for a ResultSet concurrency.

⇒ The Updatable ResultSet allows us to insert, update and delete the records using ResultSet.

Using Updatable ResultSet to update the data:

⇒ The following three steps are required to implement Updatable ResultSet:

Step 1: Move the row pointer to the row that we want to update.

Step 2: Update the column values.

-We use the following updateXxx() methods for updating the column values:

Update String value using Updatable ResultSet

updateString(int col_index, String new_value)

Update int value using Updatable ResultSet

updateInt(int col_index, int new_value)

⇒ We have all these methods overloaded taking the first arg as String i.e. col_name
Step 3: Update the row-

-We use updateRow() method of ResultSet to update the row.

Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

ResultSet rs = st.executeQuery("select eid, ename, esal from emp1");

while(rs.next())

{

	System.out.print(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getDouble(3));

   

	if(rs.getInt(1)==3)

	{

							rs.updateInt(3,90000);

							rs.updateRow();

							System.out.println("--- Updated");

	}

	else

	{

				System.out.println("Not updated");

	}

}

Q.17: What is METADATA?

  1. ResultSetMetaData
  2. DatabaseMetaData

Example: 1)

ps=conn.prepareStatement("select * from emp1");xnbsp;

ResultSet rs=ps.executeQuery(); 

ResultSetMetaData rsmd=rs.getMetaData(); 

System.out.println("Total columns: "+rsmd.getColumnCount()); 

System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1)); 

System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); 

System.out.println("max width: "+rsmd.getColumnDisplaySize(2));

System.out.println("Title for column: "+rsmd.getColumnLabel(2));

System.out.println("is readonly: "+rsmd.isReadOnly(1));

System.out.println("is writable: "+rsmd.isWritable(2));

System.out.println("is nullable: "+rsmd.isNullable(3));

Example :2)

DatabaseMetaData dbmd=conn.getMetaData();

System.out.println("Driver Name: "+dbmd.getDriverName());

System.out.println("Driver Version: "+dbmd.getDriverVersion());

System.out.println("UserName: "+dbmd.getUserName());

System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());

System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());

Q.18: What is RowSet?

A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use as compared to  a result set.

There are two types of RowSet

Q.19: What is the difference between executing, executeQuery, executeUpdate in JDBC?

execute(): it is used for any kind of SQL Query.

executeQuery() : it is used for select query.

executeUpdate(): it is used to update query.

Q.20: What is blob and clob datatypes in JDBC?

These data types are used to store large amount of data into database like images, movie etc.

Q.21: What is the function of setAutoCommit?

When a connection is created, it is in auto-commit mode.

This means that each individual SQL statement is to be treated as a single transaction.

The setAutoCommit will be automatically committed just after getting executed.

The way by which two or more statements are clubbed into a transaction to disable the auto-commit mode is :

con.setAutoCommit (false);
Once auto-commit mode is disabled, no SQL statements will be committed until we call the method ‘commit’ explicitly.

Q.22: How are JDBC Statements used?

A Statement is an object, by which we send an SQL statement to the DBMS.

We create a Statement object and then execute it.

For a SELECT Statement, the method used is executeQuery.

The Statement that creates or modifies a table is executeUpdate.

For creating a Statement object an instance of an active connection is required.

In the following code, we use our Connection object con to create the Statement object

Statement stmt = con.createStatement();

Q.23: What is servlet?

Servlet technology is used to create web application (resides at server side and generates dynamic web page).

Java Servlets are programs that run on a web server and used for developing web applications.

Q.24: How Servlet is better than CGI ?

There are many advantages of servlet over CGI.

Q.25: What is deployment descriptor?

Deployment Descriptor(DD) is an XML document that is used by Web Container to run Servlets and JSP pages. It is present  inside WEB-INF folder of application.

DD is used for several important purposes such as:

  1. Mapping URL to Servlet class.
  2. Initializing parameters.
  3. Defining Error page.
  4. Security roles.
  5. Declaring tag libraries.

Q.26: Which are the different ways to create a servlet.?

There are 3 ways to create a servlet

  1. By implementing Servlet interface
  2. By extending GenericServlet class
  3. By extending HttpServlet class

But mostly a servlet is created by extending HttpServlet abstract class.

HttpServlet gives the definition of service() method of the Servlet interface.

The servlet class that we will create should not override service() method. Our servlet class will override only doGet() or doPost() method.

When a request comes in for the servlet, the Web Container calls the servletxs service() method and depending on the type of request the service() method calls either the doGet() or doPost() method.

By default a request is Get request

Example:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class  first_serv extends HttpServlet

{

 protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException

{

       response.setContentType("text/html");

        PrintWriter out = response.getWriter();       

      out.println("xh2x Welcome x/h2x");                 

            out.close();  }}

Q.27: What is the difference between doGet() and doPost() methods in Servlet?

1. In doGet(), the parameters will be visible in the address bar, they get appended to the URL.

In doPost() parameters will not be visible in the address bar.
2.  Maximum 1024 characters can transfer through GET request.

doPost() doesn’t have any limitations.
3.  In doGet() parameters will not get encrypted so is not good for sensitive data.

In doPost() the parameters are encrypted hence it is more secure compared to doGet().
4. Method doGet() allow you to bookmark the resource. doPost() doesn’t allow bookmarks.
5.  doGet() is faster compared to the doPost() method.

Q.28: What is the The service() method in Servlet?

The service() method is the main method to perform the actual task.

The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException

{

}

The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate.

So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request.

Q.29: What is the init() method in Servlet?

The init method is designed to be called only once.

It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate.

The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException
{

// Initialization code...

}

Q.30: What is the destroy() method in Servlet?

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:

public void destroy() { // Finalization codex }

Q.31: Explain Servlets x Life Cycle.

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

The servlet is initialized by calling the init () method.

The servlet calls service() method to process a clientxs request.

The servlet is terminated by calling the destroy() method.

Finally, servlet is garbage collected by the garbage collector of the JVM.

Q.32: Which are the Servlets Tasks?

Servlets perform the following major tasks:

Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.

Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.

Process the data and generate the results.

This process may require talking to a database, invoking a Web service, or computing the response directly.

Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Q.33: What is web container?

A web container also known as a servlet container is the component of a web server that interacts with Java servlets.

A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access-rights.

A web container handles requests to servlets, JavaServer Pages (JSP) files, and other types of files that include server-side code. The Web container creates servlet instances, loads and unloads servlets, creates and manages request and response objects, and performs other servlet-management tasks.

A web container implements the web component contract of the Java EE architecture, specifying a runtime environment for web components that includes security, concurrency, lifecycle management, transaction, deployment, and other services.

Q.34: What is Session Tracking in Servlets?

Q.35: Which are the Session Tracking Techniques?

There are four techniques used in Session tracking:

  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

Q.36: What directory structure used in Servlet program?

Q.37: What is cookies in Servlet?

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

 

Advantage of Cookies:
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies:
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.

Q.38: How Cookie works?

By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.

Constructor of Cookie class

Constructor Description Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are:

public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.

public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

Q.39: How to create Cookie?

Letxs see the simple code to create cookie.

Cookie ck=new Cookie("user","supriya k");//creating cookie object

response.addCookie(ck);//adding cookie in the response

Q.40: How to delete Cookie?

Letxs see the simple code to delete cookie. It is mainly used to logout or signout the user.

Cookie ck=new Cookie(xuserx,xx);//deleting value of cookie

ck.setMaxAge(0);//changing the maximum age to 0 seconds

response.addCookie(ck);//adding cookie in the response

Q.41: How to get Cookies?

Letxs see the simple code to get all the cookies.

Cookie ck[]=request.getCookies();

for(int i=0;ixck.length;i++)

{

out.print("xbrx"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie

}

Q.42: Differentiate between a Statement and a PreparedStatement?

In Statement, a query is compiled each time and in case of PreparedStatement, query is complied only once.

So performance wise PreparedStatement is better than Statement.

Q.43: What is HttpSession interface?

1)bind objects 2) view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.

Creating a new session

HttpSession session = request.getSession();// if the session already exist, it return the existing one otherwise it creates a new session

HttpSession session = request.getSessiontrue(true);// always returns a new session

Getting a pre-existing session

HttpSession session = request.getSessiontrue(false);

Destroying a session

session.invalidate();

Q.44: How to set Session timeout in servlet?

public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.

Q.45: How can we create deadlock condition on our servlet? 

call doPost() method inside doGet() and vice a versa, it will create deadlock situation for a servlet.

Q.46: What is the difference between HttpServlet and GenericServlet in Servlet API?

GenericServlet provides framework to create a Servlet for any protocol e.g.FTP, SMTP etc, while HttpServlet is built-in Servlet provided by Java for handling HTTP requests.

Q.47: What is Servlet chaining?

In this the output of one servlet would be piped into another servlet , and the last servlet from the chain provides the output to the web browser.

Q.48: What is RequestDispatcher in Servlet?

The RequestDispatcher interface provides the facility of transmit the request to another resource it may be html, servlet or jsp. We can use this interface to include the content of another resource also. It is one of the way of servlet collaboration.

The RequestDispatcher interface provides two methods.

  1. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource on the server.
  2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource in the response.

Q.49: What is sendRedirect() in servlet?

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource like servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side as it uses the url bar of the browser to make another request. So, it can work inside and outside the server.

Example:

public class Demo extends HttpServlet{

public void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException

{

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

response.sendRedirect("http://www.yahoo.com");

pw.close();

}}

Q.50: What are different ways for servlet authentication?

HTTP Basic Authentication

HTTP Digest Authentication

HTTPS Authentication

Form Based Login:

Conclusion:

If you think we have missed anything important, please comment. Will try to accommodate it in next our part.

These are extremely useful Advance Java Interview Questions for beginners and experienced. We are sure that these questions will help you understand Advance Java and crack your interview.