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 – 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.

  • Making a connection to a database.
  • Creating SQL or MySQL statements.
  • Executing SQL or MySQL queries in the database.
  • Viewing & Modifying the resulting records.

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:

  • In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine.
  • Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database.
  • When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.

Type 2: JDBC-Native API

  • In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine.
  • If we change the Database, we have to change the native API, as it is specific to a database and they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC’s overhead.

Type 3: JDBC-Net pure Java

  • In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.
  • This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases.

Type 4: 100% Pure Java

  • In a Type 4 driver, a pure Java-based driver communicates directly with the vendor’s 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 don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

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:

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().

  • The getConnection() method of DriverManager class is used to establish a connection with the database.

Example:

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 object’s createStatement( ) method, as in the following example −

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

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              

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.

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

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 vendor’s 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 don’t 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:

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.

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 .

  • getString(1)  or rs. getString( String column_name);
  • getInt(2);   or getInt(Int column_name);

Q.14: Explain Scrollable Result SET.


Scrollable ResultSet:

  • ⇒ This type of ResultSet allows to scroll within the rows in any direction and in any steps.
  • ⇒ To get the ResultSet of the required type we need to create the JDBC Statement specifying the type.
  • The following overloaded methods of Connection can be used to do this:
  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.

Q.17: What is METADATA?

  • Metadata means information about data.
  • JDBC can provide additional information about the structure of a database and tables.(example table name, column name, type, etc)
  • JDBC provides 2 interfaces to retrieve metadata
  1. ResultSetMetaData
  2. DatabaseMetaData

Example: 1)

Example :2)

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

  • Connected A connected RowSet Object is permanent in nature. It doesn’t terminate until the application is terminated.
  • Disconnected A disconnected RowSet object is temporary in nature. Whenever it requires retrieving data from the database, it establishes the connection and closes it upon finishing the required task. The data that is modified during disconnected state is updated after the connection is re-established.

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.

  • Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
  • Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
  • Servlet can be described in many ways, depending on the context.
  • Servlet is a technology i.e. used to create web application.
  • Servlet is an API that provides many interfaces and classes including documentations.
  • Servlet is an interface that must be implemented for creating any servlet.
  • Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.
  • Servlet is a web component that is deployed on the server to create dynamic web page.

Q.24: How Servlet is better than CGI ?

There are many advantages of servlet over CGI.

  • The web container creates threads for handling the multiple requests to the servlet.
    Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low.
  • Servlets are server side programs written in Java.
  • Unlike CGI scripts, the servlet initialization code excutes only once.
  • Moreover, separate threads in the server handle each client request. This prevents the creation of unnecessary processes, thus enhancing the performance of the server.
  • In addition, Servlets inherit all the features of the Java programming language. For example, like all standard Java classes, a servlet is platform independent and can be used across different operating systems.
  • Similarly, a servlet can make use of the extensive power of Java, such as networking, multithreading, Java Database Connectivity (JDBC), internationalization, and Remote Method Invocation (RMI).

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 servlet’s 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:

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:

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:

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 code… }

Q.31: Explain Servlets – 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 client’s 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?

  • Session simply means a particular interval of time.
  • HTTP is a “stateless” protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
  • Session Tracking is a way to maintain state (data) of a user. It is also known as session management in servlet.
  • Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
  • Session Tracking is used to recognize the user, it is used to recognize the particular user.

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?

Advance Java Interview Questions - Web Structure

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?

Let’s see the simple code to create cookie.

Q.40: How to delete Cookie?

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

Cookie ck=new Cookie(“user”,””);//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?

Let’s see the simple code to get all the cookies.

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?

  • The servlet container uses this interface to create a session between an HTTP client and an HTTP server.
  • The session persists for a specified time period, across more than one connection or page request from the user.
  • In this case, container creates a session id for each user. The container uses this id to identify the particular user.
  • An object of HttpSession can be used to perform two tasks:

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

  • HttpSession object is used to store entire session with a specific client.
  • We can store, retrieve and remove attribute from HttpSession
  • Any servlet can have access to HttpSession object throughout the getSession() method of the HttpServletRequest

Creating 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:

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.

Add a Comment

Your email address will not be published. Required fields are marked *