For Course Enquiry -

+91 9985396677

Top 100 Advanced Java Interview Questions & Answers

1) What is JSP?
Answer:

JSP is the abbreviation for Java Server Pages which is used in developing web applications. It is used in creating dynamic web content. We can write the java code into the html pages with the use of JSP.

It is an extension to the servlet as it provides more features such as JSTL, expression language,etc.

It is mainly used to develop the presentation layer.

2) What are the implicit objects in JSP?
Answer:

There are a total of nine implicit objects in jsp.These are built – in objects created during the translation phase of jsp to servlet.These objects are created by the web container automatically and can be used directly in the scriptlets.

a. request – This object is an instance of HttpServletRequest and is created by the container for each request.

b. response– This object is an instance of HttpServletResponse and is associated with the response that is been sent to the client.The response object is used to set the content type and to redirect to the response page.

c. out–It is used to write the data to the buffer and send content in the response.It ia an instance of PrintWriter which contains print() and println() methods.

d. session–This is an instance of HttpSession and it is used to setthe object’s data in the session and get the users data from the session as well as it remove the attributes from session scope. It is mainly used to get the user’s information until the session is active.

e. application–It is an instance of ServletContext object and is created only once by the container when application is deployed to the server. It is mainly used to get the initialization parameters from the web.xml. It is also used to share the attributes and its values across all the JSP pages.

f. config–This is an implicit object of ServletConfig and it is used to get the initialization parameters of a particular JSP page. It is created by the web container specific to each jsp page.

g. pageContext–This is an implicit object of PageContext and is used to set,get and remove the attributes. It contains information of the directives , error page URL , etc. It has 4 scopes which are page, request, session and application scopes.

h. page–It refers to the current instance of the servlet class.

i. exception–This is used in exception handling process to display the error messages.This object is applicable only to the JSP page where the attribute “isErrorPage” is true.


3) Explain life cycle methods of JSP.
Answer:

The following are the lifecycle methods of the jsp as shown in the diagram.

 

  first step is the translation phase where the jsp is converted into Servlet.

The JSP engines compiles the servlet into the executable bytecode format(.class).

The class is loaded into the web container to process the request.

Creating a servlet instance.

The For every user request, init method is invoked where the initializations are performed such as database initialization, opening files,etc.It is called only once.

Once the JSP is initialized, it calls the service method where request is processed and response is sent to the client.

void _jspService(HttpServletRequest req,HttpServletResponse resp){

        //business logic 

}

Destroy method is invoked only once to destroy the object and perform cleanup activities.


cover image
4) Difference between include directive and include action tag.
Answer:

include directive includes the file during translation phase whereas include action includes the file during runtime.

If the included file is modified but the file which is including it is not changed, the changes will reflect only with the include action tag. While using include directive , the changes will not reflect as the jsp which included it is not changed and hence it is not translated to servlet.

Syntax of include directive:

<%@ include file="file_name" %>

Syntax of include action tag:


We can pass the parameters to the included page while using include action tag but this wont work with include directive.


5) Explain the translation phase of JSP.
Answer:

When a request is mapped to a particular jsp page, it is handled by a special servlet which checks if the servlet is older than the jsp page.If it is, then the jsp file is converted into a servlet class during translation phase.During this phase, container validates the syntax and correctness of the jsp files and tags.

The servlet class is then compiled into an executable byte code (.class file) which is loaded into the web container automatically.

6) Explain directives in JSP.
Answer:

JSP Directives provide ability to the web container on how to translate the jsp into its corresponding servlet.It provides the instructions to the container on how to transform to its respective servlet.

There are three types of directives which are enclosed in <%@ %>.

a. Page directive – It provides the attributes in key value format which applies to entire JSP page such as importing packages, defining what type of page it is , etc.

       Syntax:

<%@page attribute=”value” %>

b. Include directive - This is used to include a file into a JSP. A file to be included can be a html file, text file or another JSP. The file will be included during the translation phase.

     Syntax:

<%@include file =”file_name” %>


c. Taglib directive – It is used to define the tag library whose custom defined tags can be used in the jsp.

    Syntax:  

<%@ taglib uri=”url” prefix=”to identify the tags of this library” %>


7) What is the use of tag library in JSP?
Answer:

 A tag library consists of set of custom tags to make the development easier in JSP. It helps in faster development and also code reusability as we can use the tags in multiple JSP’s. JSTL(java standard tag library) is a tag library of JSP.

It avoids the use of scriptlet in the JSP and provides more clean and neat code.

8) Difference between JspWriter and Servlet PrintWriter.
Answer:

JspWriter – It is an abstract class and is the buffered version of the PrintWriter and it throws IOException while using the JSPWriter print method.

If the page is not buffered , output written will be written through PrintWriter directly else if page is buffered , the PrintWriter object will not be created until buffer is flushed. It internally uses BufferWriter. 

PrintWriter –It is responsible for directly writing the content in response.

9) What is a PageContext and its use?
Answer:

It is an implicit object of PageContext class. It refers to the current jsp page. We can set, get and remove attributes present in various scopes such as page,session, request and application.


10) What is JSTL?
Answer:

JSTL stands for Java Standard Tag library and it is the collection of predefined tags to simply the development in jsp. It avoids the use of scriptlet without writing java code. It contains jstl core libraries and provides ability  to use the tags which helps in writing clean and neat code.


11) What iis tag and its use.
Answer:

It helps in declaring the Java Bean to be used in JSP. It first looks for an existing object with the id, if it is not found, then it creates and instantiates the bean. This is used to declare and initialize the actual object. 

useBean is mainly used to access the java bean component inside the jsp. We can use jsp:setProperty to set the properies and jsp:getProperty to get the value of the properties.

Syntax:  


12) How to handle exception in jsp.
Answer:

 JSP contains an implicit object “exception” which is used to print the exceptions. It is an object of Throwable class and can be used only in error pages.

We can handle exceptions in two ways

a. By errorPage and isErrorPage attributes of page directive – JSP contains two attributes used in exception handling.

errorPage – used to provide url of the error page which needs to be displayed when exception occurred.

Syntax:

<%@page errorPage="url_of_error_page"%>

isErrorPage –used to mark the page as an error page where exceptions are displayed.


Syntax:

<%@page isErrorPage="true"%>

b. By element in web.xml file – We can specify the error page for each page in web configuration file.

            Syntax :

Type of Exception

Error page url

13) What is a scriptlet in jsp?
Answer:

We can write java code inside the JSP by using scriptlet tag. A scriptlet can contain any number of java code such as variable declaration and method declaration. 

Syntax:<% java code logic   %>

        Example: 

<% out.println(“Welcome To Java World”); %>

14) How to include static files in jsp?
Answer:

We can include static resources with the use of include directive. When using include directive, the content of the file is included in the current jsp during the translation phase.

Syntax:

< % @ include file="header.html" % >

Here the “file” attribute contains the relative path of the file.


15) Explain Post-Redirect-Get Pattern.
Answer:

Post-Redirect-Get is a Design Pattern which is used in preventing duplicate form submissions.

When a user tries to refresh the web page on a form submitted through POST request, it causes resubmission of the request resulting in inconsistent results.

Here the form will be submitted twice resulting in duplicity and inconsistent data.
Hence to avoid this kind of issues, we need to follow PRG Design Pattern. In this pattern, instead of returning the web page directly, it redirects to another page with Get Request where it wont cause the form to be submitted again.

cover image
16) What is JSP Declaration?
Answer:

 The declaration tag is used to declare the variables and methods along with classes inside the JSP. If we declare the variables and methods inside the declaration tag it means that the variables are declared inside the servlet class but outside the service method.

 The code which is written inside the declaration tag is placed outside the service() method of the auto generated servlet.


Syntax:

<%! 

      //code to declare and initialize variables, methods and classes

%>


17) What is a custom tag in JSP?
Answer:

A custom tag is an user defined tag which eliminates the scriptlet code. It separates the business logic from the JSP page.

A custom tag can be created using

Tag handler class – in this we specify our custom tag and what it will do when used in the JSP.

TLD File – it is a tag descriptor file which will specify the tag name, tag handler class and tag attributes.

JSP page – It will use the custom tags.


18) Define Expression in JSP.
Answer:

The code which is written in the expression tag is directly written to the response. There is no need to write out.print() to write the data. It is used to print the values of the variable.

Syntax :  <%= statement %>


19) Advantages of using JSP.
Answer:

JSP is an extension to the Servlet technology which makes development easier with the use of implicit objects, expression language and custom tags.

It mixes up the static html content with the dynamic content.

It separates the presentation logic from business logic unlike servlet which holds both.

There is no need to recompile and redeploythe project if JSP page is modified.


20) What is page directive?
Answer:

The page directive is used to provide the instructions to the container pertaining to a JSP page.

The page directives are usually placed in the start of the JSP and is in the key-value format.


It specifies the classes to be imported in the JSP , if it is errorPage , etc.

Syntax:

<%@ page attribute = "attribute_value" %>


21) Difference between response.sendRedirect() and request.forward() ?
Answer:

sendRedirect – It is method of HttpServletResponse interface which is used to redirect the request to other resourceswhich are deployed on different server or different locations.

Syntax:void sendRedirect(String url)

forward - It is a method of RequestDispatcher interface. It is used to forward the request to a resource which is in the same server. A resource can be an another JSP file, html or a servlet file.

Syntax: forward(ServletRequest request,ServletResponse response)


22) How to pass data from one JSP to another JSP.
Answer:

There are various approaches to get the data from one JSP to another.

Approach 1: Using request scope

String name = “Raju”;

request.setAttribute(“name”, name);

We can access this attribute in another jsp as request.getAttribute(“name”);

The value stored is applicable only for the current request.

Approach 2: Using session scope.

The values which are to be sent from source JSP are set using setAttribute using session object.

Example:

<% session.setAttribute(“eid”,100); %>

The target JSP can access the eid with the use of getAttribute method.

The value stored is applicable only for the current session.

Approach 3: Using application scope

The values which are to be sent from source JSP are set using setAttribute using application object.

Example: 

<%application.setAttribute(“studentName”,”Aysha”); %>

The target JSP can access the studentName with the use of getAttribute method.

The value stored is applicable for the entire application.


23) Can a JSP extend a java class.
Answer:

Yes, a JSP can extend a java class using page directives. But it is not advisable to extend java class, and we should avoid writing scriptlets in JSP.


24) How will you create an error page in JSP?
Answer:

An error page in JSP can be created by setting isErrorPage attribute to true.Once done, we can access the exception object and send the error message to the client.

Example of error Page:

<%@ page isErrorPage="true" %>

An exception has occured!

Exception is: <%= exception %>


25) What are the scripting elements in JSP?
Answer:

 Scripting elements in JSP are written within <% %>. It provides an ability to insert java code. During translation phase, the code inside <% %> will be converted to java code.

There are 5 types of scripting elements:

1. Comment

2. Scriptlet

3. Declaration

4. Expression

5. Directive.

26) How to declare comments in JSP.
Answer:

A JSP Comment is used to ignore a part of the content(statements) inside the jsp which is commented.

Syntax: <%-- JSP Comment -- %>


27) What is a java bean?
Answer:

A java bean is a POJO class which follows simple guidelines.

It implements the serializable interface to save the state of an object.

It contains a public no-arg constructor.

It contains getter and setters in order to access the private member variables


28) What are the attributes of page directive?
Answer:

Some of the attributes of page directive are 

a. isErrorPage – it returns true if the current jsp page is an error page.

b. Import – it informs the web container which classes/packages need to be imported in the JSP.

c. contentType – it specifies the format in which client and server exchange the data.

d. Buffer – it defines the buffer size which is assigned to handle the JSP page.

e. isELIgnored – it specifies if the JSP page supports expression language.


29) What is a servlet?
Answer:

 A servlet is a java program that runs on the server either web server or application server.

They are used to handle the incoming requests from the client and sends the response back to the user.

Servlets are server-side programming language. It helps in creating dynamic web application.


30) Difference between web server and application server.
Answer:

Web Server – it is mainly used to handle the HTTP requests. Its main purpose is to display the static content. It can support only web related technologies. It also supports scripting languages like PERL, PHP.

Example: Tomcat, Jetty

Application Server - It deals with several protocols and is not limited to HTTP. It provides the business logic and interaction between the user and the displayed content. These servers can perform all the operations which a web server is capable of.

Example: Jboss, WebLogic.

 

31) What is ServletConfig object?
Answer:

This object will be created during the initialization process of a servlet. It is specific to one particular servlet meaning the initialization parameters are not known to other servlets.

This object will be available as long as the servlet is executing and will be destroyed once servlet has completed its execution

Syntax:

WelcomeServlet

com.ashokit.WelcomeServlet

name

Siddhart

The init param can be accessed by using ServletConfig object


cover image
32) What is ServletContext object?
Answer:

Only one ServletContext object will be available for the entire application. It will be shared across all the servlets and JSP available in the web application.

The ServletContext parameters are specified for entire application outside of any particular servlet and are available to all the servlets within that application. It is application scoped and thus globally accessible across the pages

The context param can be accessed by using ServletContext object.

URL

jdbc:oracle:thin:@localhost:1521:test

cover image
33) What is Request Dispatcher ?
Answer:

 It is an interface which receives the request from the client and dispatches it to another resource such as a html, a servlet or a JSP.

It contains 2 methods.

a. forward (ServletRequest req, ServletResponse resp)–It is used to forward the request from one servlet to another on a server.

b. include (ServletRequest request, ServletResponse response)– It is used to include the content of a resource in the response.


34) What is inter-servlet communication?
Answer:

 It is a process where two or more servlets interact with each other to serve the client request.

 

35) Explain servlet mapping.
Answer:

It is used to map a servlet to a particular URL pattern. Whenever there is a request from the client, the web container decides which servlet to invoke based on the incoming request.

We need to register each servlet in deployment descriptor file and map each servlet to a url path.

HelloServlet

/welcome/*

36) What is a cookie?
Answer:

 Cookies are mainly used in session management. A cookie is a small piece of information which is sent by the servlet to the web browser and saved in the browser. The client sends the cookie back to the server for all subsequent requests until the cookie is valid. The web container checks for the cookie in the request header and gets the session information from the cookie.

A cookie has a name and unique session id as its value. Cookies remain active until the browser is open.


37) Difference between Generic and HTTP Servlet.
Answer:

Generic Servlet– It is protocol independent and can handle all types of protocols like http,ftp,smtp,etc. It is a direct subclass of Servlet interface.

GenericServlet is an abstract class which implements Servlet, ServletConfig and Serializable interface. It contains only service method and does not support doGet() and doPost() methods.

HttpServlet–It is protocol dependent and is specifically tied to HTTP protocol. Itis an abstract class which extends GenericServlet and implements Serializable interface. It supports service(),doGet() and doPost() methods.

38) How can you create a session in Servlet?
Answer:

 A HttpSession object is mainly used for session management. Whenever a user enters the website for the first time, a unique session id is created for the user and sent as a response in the form of a cookie.

The HttpSession remains alive until it reaches the timeout mentioned in web.xml. To create or gain access to existing session, we can use 

HttpSession mySession = request.getSession();


39) Explain the working of a service method in servlet.
Answer:

This is the entry point method to handle the requests. The service method redirects the request to the appropriate handler method based on the type of the request.

If the client sends a GET request, service method calls doGet() method and if the client sends  a POST request , it calls the doPost() method. The service method is called for every client request.


40) What is URL Rewriting?
Answer:

 If the cookies are disabled by the user, then there is no way to track the session. URL Rewriting Is one of the way to perform session management.

In url rewriting, a token is appended at the end of the url. It is in the key value pair and we can append multiple data at the end of the url. It is used to send the data from one servlet to another servlet.

Syntax:

URL?paramName1=paramValue1& paramName2=paramValue2


41) What is a deployment descriptor?
Answer:

It is a web.xml file which contains the information on which servlet is mapped to which URL pattern. The web server uses this xml configuration to identify which Servlet can handle the client request. The root tag in web.xml is web-app.

Sample Deployment Descriptor:

servletName

servletClass

servletName

*.*


42) What is loadOnStartup in servlet?
Answer:

 The servlet is not loaded until the web container receives a request for that particular servlet.

But if we specify , then the servlet will be loaded by the web container as soon as the server starts.

If load-on-startup >0, the web server will load the servlet when the application is deployed and if it is less than 0, then container will load whenever it wishes to.


43) Explain difference between GET and POST method.
Answer:

GET – It is used to request for data from a specific resource. It appends the form data to the URL in key-value pair. GET method can be used if the data in the URL to be appended is not huge and also it should be used only if the data being sent in the URL is not confidential as in GET, the url data is exposed in the URL bar.

POST-In POST request, data is sent to the server to create/update a resource. The request data is sent in the request body of the HTTP request. There is no restriction while sending data in the request body and is highly secured.


44) What do you mean by non-idempotent method?
Answer:

 POST is mainly used to create a new resource on the server. When the POST method is invoked multiple times, it will create resource multiple times and this is why POST is a non-idempotent method.

An idempotent HTTP method is that it can be called many times without change in the result whereas in case of POST, a new resource will be created.


45) What is servlet lazy loading?
Answer:

Lazy loading means the servlet is not loaded during the application startup. It would be loaded when the client requests for it the first time.


46) When deadlock situation will arise in Servlet?
Answer:

Deadlock can occur in Servlet when doGet() method calls doPost() and vice-versa.

47) Explain Session Tracking.
Answer:

Since HTTP is a stateless protocol, it treats every request coming to the server as a new request and does not keep any information about the previous requests.

Session Tracking is a way to keep or maintain the user data with the help of some techniques.

There are 4 ways which helps in session management.

a. Cookies

b. Hidden Form Fields

c. URL Rewriting

d. Session


48) What is ServletFilter?
Answer:

ServletFilter are also java classes which acts as an interceptor between the client request and the resource at back end. It helps in pre-processing and post-processing of the request. It also helps in manipulating the response before it is sent back to the client. These classes are executed before handing over the request to the corresponding servlet.

It helps in performing filtering tasks such as validating the client, logging , etc.

Filtering is performed in doFilter() method.


49) Explain lifecycle of a servlet.
Answer:

The entire lifecycle of the servlet is managed by the web container.

a. Loading a servlet class

The webcontainer is responsible to load the servlet class in one of the following stages

If the load-up-startup element is zero or greater than zero , then it will load the servlet during application startup.

If it is not loaded in the above stage, the webcontainer will load the servlet when the incoming request comes to that particular servlet.

       Once the servlet class is loaded, the web container creates an instance of the Servlet. 

b. Initializing a servlet

Once the servlet object is instantiated, it initializes the Servlet using init method. The web container initializes the Servlet object using init(ServletConfig).The init method is called only once which is used to initialize the database connection, etc.

c. Handling the client request.

Once the servlet is initialized, it is ready to handle the client requests. This is done with the help of service method which takes ServletRequest and ServletResponse as parameters.

d. Destroy the servlet.

This method is invoked only once by the web container which decides to destroy the servlet after completion of its operations.


cover image
50) What is a WAR file.
Answer:

Web application archive (WAR) contains static and dynamic files in the project. It contains servlets,jsps , css ,html, javascript files etc.

WAR file combines all files into a single unit.


51) Explain MIME Type.
Answer:

Content Type is also known as MIME Type which stands for Multipurpose Internet Mail Extension. The servlet gives instruction to the browser to display the content in the format which it sends in the response object.

Eg: response.setContentType(“text/plain”);


52) Are servlets thread-safe?
Answer:

 By default, servlets are not thread-safe. Servlets are usually multi-threaded. The web container usually manages concurrent request by creating a thread for every request. A single instance of the servlet can handle multiple requests.

We can make a servlet thread safe by implementing SingleThreadModel but it is deprecated.


53) How to read form data in the servlet.
Answer:

In order to read the values of the form, we can use the methods provided by HttpServletRequest interface.

request.getParameter(String name) – gets the value of the field which has the specified name.

request.getParameterValues(String name) – it returns an array of String object which contains all the values which has same field name.


54) How to create a cookie using Servlet?
Answer:

A cookie can be created as below

      Cookie cookie = new Cookie(“username”,”Pooja”);

      We can send the cookie from the servlet using response.addCookie(cookie) method.

55) How to set session timeout in Servlet?
Answer:

By default, the web container provides a default time out of a session as 30 minutes for all web application.

We can change the timeout using xml and also programmatically.

Xml:

10

The session timeout is in minutes.

Programmatically:

HttpSession session = request.getSession();

session.setMaxInactiveInterval(10*30);

Here the time format is in seconds.

56) Who is responsible to create object of a servlet?
Answer:

The web container is responsible for creating the servlet instance. When a request comes in for a particular servlet, the server hands over the request to the web container which is responsible in instantiating the servlet object.


57) What is servlet collaboration?
Answer:

The process of sharing information from one servlet to the another on a same server is referred to as servlet collaboration.

The collaboration can be achieved in 2 ways.

Using methods of RequestDispatcher

Using method of HttpServletResponse

58) Can you call a JSP from a servlet?
Answer:

Yes, a JSP can be invoked from a servlet as below by using forward method of RequestDispatcher as below.

RequestDispatcher dispatcher = getRequestDispatcher("URL to jsp");

dispatcher.forward(request, response);

Another way is using the sendRedirect method.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.sendRedirect("jsp_file_name");

}


59) Difference between cookie and session?
Answer:

 Cookies – These are client-side files which contains user information. A cookie is a small file which has a size of 4 KB. The cookies help to keep track of the user’s browsing history.

Session –These are server-side files which contains user information which will be used by multiple pages across the application. The session starts when the user logs into the application and ends when the user logs out of the application.


60) Explain the purpose of servlet container.
Answer:

The servlet or web container is a component of a web server that interacts with the servlet. It is used to manage the lifecycle of a servlet. It also helps in mapping the client request to a particular servlet.


61) Explain Servlet Listener.
Answer:

 Listeners are java classes which listens to particular events and when that event occurs, it triggers a functionality. There are multiple listeners available.

Some of the most important Listener interfaces are -

ServletContextListener

ServletContextAttributeListener

HttpSessionListener

HttpSessionAttributeListener

HttpSessionBindingListener

ServletRequestListener

ServletRequestAttributeListener


62) What is servlet chaining?
Answer:

Servlet chaining is the process where two or more servlets interact to serve a single client request. Here the output of one servlet is sent to another servlet as input.This process continues until the last servlet is reached. The output is then sent back to the client.

63) Explain the life cycle of a ServletFilter.
Answer:

Servlet filters are java classes which are used to perform pre-processing and post-processing logics. It is used to manipulate the request/response object which is coming to the web application.

Filters can be implemented in scenarios where the client should access a particular servlet only if client is a valid one.

The lifecycle of a filter is also managed by the web container. Every filter must implement the Filter interface.

The following are the life cycle methods of a filter.

a. init – This method is called only once to perform initialization tasks.

b. doFilter –It is invoked after the init method. It is called each time when filter needs to perform some operation. It contains the functionality of a filter to perform pre processing of a request and post processing of a response.

c. destroy – it is called only once to perform clean up activities before the container removes the filter instance.


64) What is JSessionId ?
Answer:

 JSessionId is a cookie generated by the web container which is sent as a response to the client. It is used in session management. Whenever client requests comes in, the web server looks for the JsessionId and based on it is considers as a new or old request.


65) How to invalidate a Session object?
Answer:

A session can be invalidated using session.invalidate() method. All objects associated with the session will be removed.


66) Describe Hidden Form Fields.
Answer:

This is one of the ways to implement session management. It is used to store the session information of a client in the hidden fields. The user information is captured in the hidden field and retrieved from another servlet.

Syntax:

<input type="hidden" name="uname" value="abc">


67) Define getInitParameter() method.
Answer:

 It is used to return the value of the given parameter as String or null if the parameter does not exist in deployment descriptor file.

Eg :

empName

Raju

It returns Raju while calling getInitParameter(“empName”)


68) Difference between PrintWriter and ServletOutputStream.
Answer:

ServletOutputStream is mainly used for writing the binary data in the response whereas PrintWriter is used to write textual data.


69) How to get the server information in a servlet.
Answer:

In order to display the name of the server, we can use the method getServerName()  and to get the port details of the server , use method getServerPort() available in HttpServletRequest interface.


70) How to get the client information on the server.
Answer:

A servlet can use getRemoteAddr() method to retrive the IP address of the client and getRemoteHost() to fetch hostname of the client machine.

public String ServletRequest.getRemoteAddr()

public String ServletRequest.getRemoteHost()


71) Can you override the service () method.
Answer:

It is not a good practice to override the service() method. The service() method of GenericServlet can be overloaded to support any type of protocols. However we need to override the doXXX() methods of the HttpServlet to write the business logic . The service method invoked by the servlet container can call the doXXX methods based on the type of the request.


72) What is URL Encoding.
Answer:

It is a mechanism in which the special characters are converted to an universally accepted format which will be used by client browsers. It is used mainly while submitting the form data. 


73) What are the different ways to authenticate a servlet?
Answer:

The different ways to authenticate a servlet are:

HTTP Digest Authentication

HTTP Basic Authentication

HTTPS Authentication

Form-based Authentication


74) Difference between client side and server-side validation.
Answer:

When you enter data, the browser and the web server will check to see whether the data is in correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side validation.


75) What is JDBC?
Answer:

JDBC Stands for Java Database Connectivity. It is used to connect and execute the query with the database. It is an API which communicates with the database with the help of JDBC Driver. We can save/update/delete/retrieve the data from the database using JDBC API.


76) What is JDBC Driver and its types.
Answer:

A JDBC Driver is a software which enables a java program to interact with the database. There are 4 types of JDBC Drivers.

JDBC-ODBC Bridge Driver

JDBC Native API

JDBC Network Protocol Driver

Thin Driver


77) How to connect Oracle database with java.
Answer:

In order to connect with Oracle database, first step is to download oracle jdbc driver in the classpath. Once the driver is added to classpath, we need to write program as below.

a. Load the driver class using Class.forName method.

b. Create a connection object to establish connection with the database.

c. Create a statement object.

d. Execute the query.

e. Close the connection.

78) What are JDBC Statements?
Answer:

 A statement is an interface in JDBC which is used to execute SQL queries in the database. There are three types of JDBC statements.

1. Create Statement – It is used to execute the static queries and it does not take IN and OUT parameters.

Example:Statement statement = connection.createStatement();

2. Prepared Statement–It is mainly used for inserting dynamic values into the SQL statements.

It takes only IN parameters which can be passed during runtime in  the placeholder of “?”.

The main advantage of going for prepared statement is we can pass multiple parameter values into the statement and can be reused.


Example:

String query = "insert into EMP(name, age,dept)VALUES(?, ?)";

Statement pstmt = con.prepareStatement(query);

pstmt.setString(1,"Krishna");

ptstmt.setInt(2,30);

pstmt.setString(3,"IT");


3. Callable Statement–This is mainly used to execute a procedure or a function. A procedure is a set of SQL statements which are executed multiple times as a loop. It supports IN and OUT parameter.

Example : CallableStatement stmt = con.prepareCall("{call Procedure_name(?, ?}");


79) What is a resultSet?
Answer:

 A ResultSet contains the row data after executing the SQL queries. The records are returned based on the conditions passed in the query. The resultset can be iterated to fetch the rows of the table.

80) What are the types of resultSet?
Answer:

There are three types of ResultSet.

1. FORWARD-ONLY – In this, the cursor can move only in forward direction in the resultset.

2. SCROLL-INSENSITIVE – This type is scrollable and can move in any direction.It is insensitive meaning if there is any change in the database, it would not affect the resultset when it is open.

3. SCROLL-SENSITIVE – This type is also scrollable and can move in both forward and backward direction. The resultset reflects the changes which are made to the database while it is open.


81) What is setAutoCommit(false)
Answer:

 If we pass false to this method, it turns off the auto commit feature.


82) What is database connection pooling.
Answer:

It is a technique where a pool of connection objects are created. It follows the object pool design pattern. In this design, objects are created in advance and placed in the pool container.Whenever the applications requires a connection object, it picks it from the pool container. This mainly improves the performance of the java application. The object created in the pool container can be reused to perform multiple operations.


83) What is DriverManager class.
Answer:

It acts as an interface between the application and the JDBC driver. The main purpose is load the JDBC driver in order to establish a connection with the database.


84) Why are prepared statements faster?
Answer:

When using a PreparedStatement, the query is compiled only for the first time and stored in the database server. The values in the “?” placeholder are supplied later which makes the execution faster.


85) What is JDBC Savepoint?
Answer:

A Savepoint object is used to mark intermediate point within the current transaction. When a transaction is rolled back to a savepoint all changes made after that savepoint are undone.

A savepoint can be created in database using:setSavepoint(String savepointName).


86) Why should we close a database connection?
Answer:

We always need to close the connection explicitly so as to prevent memory leakage and to end the database connection once you are done with it. We need to use close() method to close the connection which in turn will close ResultSet and Statement object automatically.

87) What is setFetchSize() and setMaxRows() methods?
Answer:

setFetchSize(int)– it defines the number of rows which will be fetched from the   database when the ResultSet need more rows.

setMaxRows(int)– it specifies how many rows, a resultset can contain at a time. If the limit is exceeded, the rows are ignored.


88) Difference between RowSet and ResultSet?
Answer:

Rowset – It does not maintain connection with the database and hence it is serialized form of ResultSet. It can be passed over the network. It is scrollable and can be updated.

ResultSet – It maintains a connection with the database, and hence it cannot be serialized. It is not possible to pass ResultSet object from one class to another class. It is non-scrollable and cannot be updated.


89) Explain CLOB and BLOB DataTypes.
Answer:

 CLOB – It refers to as Character Large Object and holds large amount of text data.This is mainly used to store large documents such as PDF’s , word documents,etc.

BLOB – It refers to as Binary Large Object. It holds a large amount of binary data. We can store                  videos, images, audio files as binary streams


90) Difference between java.util.Date and java.sql.Date.
Answer:

java.util.Date represents the date along with time whereas java.sql.Date represents only the Date.


91) What is dirty read in database?
Answer:

A dirty read problem occurs when one transaction is permitted to read the data that is being modified by another transactionand has not committed yet and both are running concurrently.

The problem will not occur if the transaction which modifies the data has been committed. 

Example: 

Alice and Bob start two database transactions.Alice modifies the company name of a record to "ABC COMPANY". Bob reads the uncommitted record.

If Alice commits her transaction, everything is fine. 

But if Alice rolls back, then Bob will see a record which no longer exists in the database.


92) Working of cursor in scrollable resultset?
Answer:

ResultSet is not scrollable and not updatable by default, which means the resultset can move only in forward direction (first row to last row).  

A cursor can move in both  forward and backward direction by using the result type as 

TYPE_SCROLL_INSENSITIVE 

TYPE_SCROLL_SENSITIVE


93) What is locking system in JDBC.
Answer:

A lock is a mechanism in which multiple users cannot access a resource. There are 2 types of locking.

Optimistic Locking – This locks the record when performing UPDATE operation.It does not use locks on SELECT records.

Pessimistic Locking –This type of locking locks the record as soon as it selects the row to update. This mechanism provides consistent results.


94) How to rollback a JDBC Transaction?
Answer:

Rollback is mainly called when you get one or more SQL exception in transaction, then the transaction gets aborted and starts from the beginning. This is the only way to know what has been committed and what not committed. 

We can rollback the modifications in the database up to a particular save point by passing the Save points name as a parameter as written below


Syntax:  connection.rollback("Save point name");


95) Difference between execute, executeQuery and executeUpdate methods.
Answer:

 execute (): This method is used to execute SQL DDL statements, it returns a boolean value specifying whether the ResultSet object can be retrieved.If it returns true, then we can fetch result set using getResultSet method. 

executeUpdate(): This method is used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected.it cannot be used on select queries.

executeQuery(): This method is used to execute select statements . It fetches Result set from the database.


96) What are JDBC Exceptions.
Answer:

JDBC Exception handling is very similar to the Java Exception handling.If the exception occurred due to Database connectivity or anything related to DB, it will come under SQLException(java.sql.SQLException).

Common JDBC exceptions are:

SQLNonTransientException: This type of exception will be thrown in an instance where a retry of the same operation would fail unless the cause of the SQLException has been corrected.

SQLTransientException: This type of exception will be thrown when a previously failed operation is able to succeed when we re-tried the operation again without any change in application.

SQLRecoverableException: This type of exception will be thrown when a previously failed operation can succeed when we re-tried the operation again with any change in the application and also current connection should be closed and the new connection should be opened.

97) How can you view a resultSet?
Answer:

 A resultSet can be viewed by using the column name and by using the column index.

Eg :  resultset.getString(“column name”);

resultset.getInt(1); 

98) What is JDBC Transaction?
Answer:

JDBC Transaction:

A transaction is a logical unit of work.When one of the step fails then all the work done from save point will be reversed and all DB transactions will be reversed and Table will be restored to old state.

auto-commit mode : By default, JDBC uses an operation mode called auto-commit. This means that every update to the database is immediately made permanent.

Savepoints: Savepoints allow to set the "staging points" in a transaction. Savepoints are checkpoints that the application can roll back to without throwing away the entire transaction.


99) Explain MVC Model and its use.
Answer:

 MVC stands for Model View Controller which is an architectural pattern. It is mainly designed to separate presentation layer from the business layer.

Model – is mainly used for business logic separation. It contains the service and persistence layer.

View – it is responsible to send the model data in a presentable format.

Controller –it acts as an intermediate between model and controller.Its main purpose is to handle the incoming client requests. Whenever a client requests for a resource, it checks for the url pattern and maps to corresponding servlet


cover image
100) Advantages of MVC Design Pattern.
Answer:

 Advantages of using MVC Design

It helps in faster development of the web-application

It separates the business logic from the presentation logic.

It is easy to maintain.

A programmer need not be aware of the front end technologies to design a view component.