You are on page 1of 23

Enterprise Programming

Question Bank

MCQs
1. Which of the following best describes the purpose of a JDBC Driver?
A. To create dynamic web pages B. To manage database connections in Java applications.
C. To design user interfaces for desktop applications. D. To generate HTML code for web pages.

Answer: B. To manage database connections in Java applications.

2. When destroy() method of a filter is called?

A) The destroy() method is called only once at the end of the life cycle of a filter

B) The destroy() method is called after the filter has executed doFilter method

C) The destroy() method is called only once at the begining of the life cycle of a filter

D) The destroyer() method is called after the filter has executed

Answer: A) The destroy() method is called only once at the end of the life cycle of a filter

Explanation: destroy() is an end of life cycle method so it is called at the end of life cycle.

3. What is the purpose of JSP tags like and in a JSP page?

A. They are used for including external JavaScript files. B. They define Java classes in the JSP page.

C. They embed Java code and expressions into the HTML page. D. They create custom JSP components.

Answer: C. They embed Java code and expressions into the HTML page.

4. Which of the following best describes a Servlet in Java?

A. A Java program that runs on a web server and processes client requests.

B. A Java framework for building desktop applications.

C. A component for rendering user interfaces in Java applications.

D. A JavaScript library for enhancing web page interactivity.

Answer: A Java program that runs on a web server and processes client requests.

5. “request” is instance of which one of the following classes?

A) Request B) HttpRequest C) HttpServletRequest D) ServletRequest

Answer: C) HttpServletRequest

6. What is the primary role of the Spring Framework in Java?

A. To create web pages using JSP.


B. To manage database connections.

C. To provide a container for managing JavaBeans.

D. To facilitate the development of enterprise-level Java applications.

Answer: D. To facilitate the development of enterprise-level Java applications.

7. Which one is the correct order of phases in JSP life cycle?

A) Translation,Initialization, Cleanup, Compilation, Execution

B) Initialization, Compilation, Translation,Cleanup, Execution

C) Translation, Compilation, Initialization, Execution, Cleanup

D) Cleanup, Compilation, Initialization, Translation,Execution

Answer: C)Translation, Compilation, Initialization, Execution, Cleanup

8. What is Hibernate in Java?

A. A framework for building user interfaces in Java applications.

B. A framework for managing database connections.

C. A framework for writing JSP pages.

D. An object-relational mapping (ORM) framework for Java.

Answer: D. An object-relational mapping (ORM) framework for Java.

9. How constructor can be used for a servlet?


A. Initialization and Constructor Function B. Setup() method C. Initialization D. Constructor function

Answer: A)Initialization and Constructor Function

10. What types of dependency injection does Spring support?

A) Based on the constructor and setters B) Based on the constructor, setters, and getters

C) Based on setters, getters, and properties D) Based on the constructor, setters, and properties

Answer: A) Based on the constructor and setters

11. What are the major components of the JDBC?

A) DriverManager,Statement and ResultSet

B) DriverManager,Driver,Connection,Statement and ResultSet

C) DriverManager,Connection,Statement and ResultSet

D) DriverManager,Driver,Statement and ResultSet

Answer: B) DriverManager,Driver,Connection,Statement and ResultSet

11. Annotation for Controller Class.


A) @Before B) @Controller C) @After D) @Exception

Answer: B) @Controller

12. Which driver is known as the thin driver in JDBC?


A) Type 1 driver B) Type 2 driver C) Type 3 driver D) Type 4 driver

Answer: D) Type 4 driver

13. Which tag is used to execute Java source code in JSP?


A) Expression tag B) Scriplet tag C)Declaration tag D)None of above

Answer: B) Scriplet tag

14. Select the packages in which JDBC classes are defined?

A. jdbc and javax.jdbc/jakarta.jdbc B. rdb and javax.rdb/jakarta.rdb

C. jdbc and java.jdbc.sql/jakarta.jdbc.sql D. sql and javax.sql/jakarta.sql

Answer: D. sql and javax.sql/jakarta.sql

15. Which of the following is not a valid statement in JDBC?

A) Statement B) PreparedStatement C) QueryStatement D) CallableStatement

Answer: C) QueryStatement

16. Which of the following code is used to get an attribute in a HTTP Session object in servlets?

A) session.getAttribute(String name) B) session.alterAttribute(String name)

C) session.updateAttribute(String name) D) session.setAttribute(String name)

Answer: A) session.getAttribute(String name).

17. Which of the following is not a directive in JSP?

A) page directive B) include directive C) taglib directive D) command directive

Answer: D) command directive

18. Which of the following is the name of Hibernate XML configuration file?

a) hibernate.config.xml b) hibernate.cfg.xml c) hibernate.cg.xml d) All of the above

Answer: b) hibernate.cfg.xml

19. What is the purpose of the Spring IoC container?

a) To manage the lifecycle of beans and their dependencies

b) To handle the configuration of the application

c) To provide a caching mechanism for the application

d) To provide a security mechanism for the application

Answer: a) To manage the lifecycle of beans and their dependencies


Fill in the blank Question with Answer

1. To add a dependency to a Maven project, you specify it in the ____________ section of the project's
POM file.

Answer: dependencies

2. Servlets are Java classes that are used to extend the functionality of a web server. They handle
_________ requests and generate dynamic web content.

Answer: HTTP

3. The Spring Framework is a comprehensive framework for building Java applications. It provides
support for _____________, aspect-oriented programming, and more.

Answer: dependency injection

4. Hibernate is an Object-Relational Mapping (ORM) framework for Java. It allows developers to map
Java objects to _______________ databases.

Answer: relational

5. In Spring, the _________ design pattern is widely used to manage the lifecycle of objects and provide
a flexible way to create and manage beans.

Answer: Singleton

6. A JDBC _______________ is a database-specific driver that facilitates communication between Java


applications and databases.

Answer: Driver

7. JSP pages are typically compiled into _______________ code by the application server.

Answer: Servlet

8. The _______________ method of the HttpServlet class is responsible for handling HTTP GET
requests.

Answer: doGet()

9. Hibernate provides a powerful and flexible way to perform _______________ operations on


relational databases.

Answer: CRUD (Create, Read, Update, Delete)

10. In Spring, beans are typically configured in an XML file or using _______________ annotations.

Answer: Java

11. Maven is a powerful project management tool that is based on ________ Who is responsible to create
the object of servlet?

Answer: POM (project object model).


12. The -------- elements provides the ability to insert java code inside the jsp.

Answer: scripting(scriptlet tag, expression tag, declaration tag)

13. ________object is used to create SessionFactory object in Hibernate?

Answer: Configuration

14. IOC (Inversion of Control) and DI (Dependency Injection) is a ---------- to provide loose coupling.

Answer: design pattern

15. _________is the update method for PreparedStatement?

Answer: executeUpdate();

16. ___________is responsible to create the object of servlet?

Answer: The web container or servlet container.

17. ________ is directive elements of jsp.

Answer: page, include, taglib.

18. Spring MVC Framework is designed based on ___________Design Pattern

Answer: Model-View-Controller (MVC)

One Line Question With Answer

1. What is Maven?

Answer: Maven is a build automation and project management tool used primarily for Java projects.

2. Whar tag is used to the output stream of the response. So you need not write out.print() to write
data. It is mainly used to print the values of variable or method.

Answer: JSP expression tag - <%= statement %>

3. Explain the difference between HttpServlet and GenericServlet in Java Servlets.

Answer: HttpServlet is a subclass of GenericServlet that adds support for HTTP-specific features like
handling HTTP methods (GET, POST) and sessions, whereas GenericServlet is protocolindependent and
suitable for non-HTTP protocols.

4. What is Inversion of Control (IoC) in the context of the Spring Framework, and how does it
facilitate loose coupling?

Answer: IoC is a design principle where the control of object creation and lifecycle is shifted from the
application code to the framework. Spring achieves this through Dependency Injection, allowing
components to be loosely coupled by having their dependencies injected rather than created within the
class.

5. What is the JSTL (JavaServer Pages Standard Tag Library)?


Answer: JSTL is a collection of custom tags and functions that simplify common tasks in JSP, like
looping and conditional statements.

6. Explain the difference between a Statement and a PreparedStatement in JDBC, and when
would you choose one over the other?

Answer: A Statement is used for executing static SQL queries, whereas a PreparedStatement is used for
precompiled SQL queries with placeholders. PreparedStatement is preferred for its performance and
protection against SQL injection, making it suitable for dynamic queries with user inputs.

7. What is a PreparedStatement in JDBC?

Answer: A PreparedStatement is used to execute precompiled SQL queries with parameters.

8. What is the role of JSP tags like?

Answer: These tags are used to embed Java expressions or variables into the HTML.

9. What is the purpose of the init() method in a Servlet?

Answer: The init() method initializes a Servlet when it's loaded into memory.

10. What is the purpose of the Spring Bean Factory?

Answer: The Spring Bean Factory manages the lifecycle of Spring beans.

11. How does Hibernate map Java objects to database tables?

Answer: Hibernate uses XML mapping files or annotations to map Java classes to database tables.

12. What is the method used retrive data from DB?

Answer: public ResultSet executeQurey();

13. What is the method can be used to get the value of "form" tag parameter to servlet?

Answer: request.getParameter()

14. Write the declaration tag of JSP?

Answer: <%! "Declaration tag" %>

15. Hibernate is a ________?

Answer: ORM Tool

16. What is the purpose of the Spring MVC module?

Answer: To provide a web framework for building web applications.

17. What is the JDBC?

Answer: JDBC stands for Java Database Connectivity.

JDBC is a Java API that communicates with the database and execute SQL query.

18. What is a JDBC driver and how many JDBC drivers are available?
Answer: JDBC driver contains classes and interfaces that help Java application and database.

There are 4 types of JDBC drivers.

Type 1 driver or JDBC-ODBC bridge driver.

Type 2 driver or Native-API, partly Java driver.

Type 3 driver or Network Protocol, pure Java driver.

Type 4 driver or Native-protocol, pure Java driver.

19. How can I connect MySQL or Oracle with Java?

//for MySQL

try {

Class.forName ("com.mysql.jdbc.Driver");

con=DriverManager.getConnection ("jdbc: mysql://localhost:3306/dbanme", "username",

"password");

Statement st=con.createstatement ();

Resultset rs=st.executeQuery ("select * from user");

rs.next (); catch (ClassNotFoundException e) {

System.err.println ("ClassNotFoundException in get Connection," + e.getMessage()); }

catch (SQLException e) {

System.err.println ("SQLException in getConnection," + e.getMessage ()) ;}

//for oracle

try

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

con= DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:dbname",

"username", "password");

Statement st=con.createstatement();

Resultset rs=st.executeQuery("select * from user");

Rs.next();

} catch (ClassNotFoundException e) {
System.err.println("ClassNotFoundException in get Connection," +e.getMessage()); }

catch (SQLException e) {

System.err.println("SQLException in getConnection, " + e.getMessage()); } return con;

Code explanation

Class.forName creates an instance of JDBC driver and register with DriverManager.

getConnection() method always establishes a connection to a database.

We need to create a Statement object from above connection object.

The statement will return resultset object. ResultSet.next() means If the result set is still returning row.

20. Which JDBC driver is the fastest driver?

Answer: Type 4 driver or Native-protocol, pure Java driver, is the fastest driver.

21. What are the JDBC API components?

Answer: There are four types of components

JDBC API

JDBC Driver Manager

JDBC Test Suite

JDBC-ODBC Bridge

22. What are the JDBC statements?

Answer: There are 3 types of JDBC Statements, as given below:

Statement: It will execute SQL query (static SQL query) against the database.

Prepared Statement: Used when we want to execute SQL statement repeatedly. Input data is dynamic
and taken input at the run time.

Callable Statement: Used when we want to execute stored procedures.

23. How can we execute stored procedures?

Answer: Stored procedures can be executed using JDBC callable statement. Here is the code.

Connection conn = null;

CallableStatement callStmt = conn.prepareCall("{call myStoreproc(?, ?)}");

callStmt.setString(1, "abcdefg");

24. What are the advantages of using PreparedStatement in Java?

Answer: Prepared Statement is used to execute same SQL statements repeatedly. The preparedStatement
is compiled only once even though it used “n” number of times
25. What is ResultSet?

Answer: The java.sql.ResultSet interface means the result set of a SQL query. It means a cursor is
pointing a row of a table; it points to before the first row.

26. What are types of ResultSet?

Answer: There are three types of ResultSet is available. If we do not declare any ResultSet that means we
are calling TYPE_FORWARD_ONLY

TYPE_FORWARD_ONLY: cursor can move only forward.

TYPE_SCROLL_INSENSITIVE: cursor can move forward and backward but not sensitive.

TYPE_SCROLL_SENSITIVE: cursor can move forward and backward, but it is sensitive

27. Explain the difference between RowSet vs. ResultSet in JDBC?

Answer: In a ResultSet handle connection to a DB, we cannot make Result as a serialized object.

Because of above issue, we cannot pass Resultset across the network.

RowSet extends the ResultSet interface, so it holds all methods from ResultSet. RowSet is serialized.

So, we can pass Rowset from one class to another class because it has no connection with the database.

28. Why would you use setAutoCommit(false) in JDBC?

Answer: If you want to turn Off the Auto Commit then set connection.setAutoCommit(false)

29. What are database warnings in JDBC and how can we handle database warnings in JDBC?

Answer: SQL warning or Database warning is the subclass of SQLException class. We can handle

it by using getWarnings() method on Connection, Statement, and ResultSet

30. Can I get a null ResultSet?

Answer: No, we cannot get null Resultset. ResultSet.next() can return null if the next record does not
contain a row.

31. What do you mean by Metadata and why we are using it?

Answer: Metadata means data or information about other data. We use metadata to get database product
version, driver name, the total number of tables and views.

32. What is the difference between executing, executeQuery, executeUpdate in JDBC?

Answer:

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

executeQuery() : it can be used for select query.

executeUpdate(): it can be used to change/update table.


33. What is database connection pooling? Advantages of using a connection pool?

Answer: Connection pooling means connections will be stored in the cache and we can reuse them

in future.

Advantage:

It is faster Connection pooling becomes easier to diagnose and analyze database connection.

34. What is the function of DriverManager class?

Answer: It is an interface between user and drivers. DriverManager tracks all the activity between a
database and the appropriate driver.

35. What is the meaning of batch updates?

Answer: Batch updates means executing a set/group of SQL queries all at once.

Batch updates can be used only for insert, update and delete but not for select query.

36. How many packages are available in JDBC API?

Answer: Two types of packages are available in JDBC API

java.sql

javax.sql

37. What is JDBC?

Answer: JDBC is a Java API that is used to connect and execute the query to the database. JDBC API
uses JDBC drivers to connect to the database. JDBC API can be used to access tabular data stored into
any relational database.

JDBC (Java Database Connectivity) More details.

38. What is JDBC Driver?

Answer: JDBC Driver is a software component that enables Java application to interact with the
database. There are 4 types of JDBC drivers:

JDBC-ODBC bridge driver: The JDBC-ODBC bridge driver uses the ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of the thin driver. It is easy to use and can be easily connected to any
database.

Native-API driver (partially java driver): The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into native calls of the database API. It is not written
entirely in Java. Its performance is better than JDBC-ODBC bridge driver. However, the native driver
must be installed on each client machine.

Network Protocol driver (fully java driver): The Network Protocol driver uses middleware (application
server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is
entirely written in Java. There is no requirement of the client-side library because of the application server
that can perform many tasks like auditing, load balancing, logging, etc.
Thin driver (fully java driver): The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as the thin driver. It is entirely written in Java language. Its
performance is better than all other drivers however these drivers depend upon the database

39. What are the steps to connect to the database in java?

Answer:

Registering the driver class: The forName() method of the Class class is used to register the driver
class. This method is used to load the driver class „dynamically‟. Consider the following example to
register OracleDriver class.

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

Creating connection: The getConnection() method of DriverManager class is used to establish the
connection with the database. The syntax of the getConnection() method is given below.

1) public static Connection getConnection(String url)throws SQLException

2) public static Connection getConnection(String url,String name,String password) throws SQLException

Consider the following example to establish the connection with the Oracle database.

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");

Creating the statement: The createStatement() method of Connection interface is used to create the
Statement. The object of the Statement is responsible for executing queries with the database.

public Statement createStatement()throws SQLException

consider the following example to create the statement object

Statement stmt=con.createStatement();

Executing the queries: The executeQuery() method of Statement interface is used to execute queries to
the database. This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method is given below.

public ResultSet executeQuery(String sql)throws SQLException

Example to execute the query

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

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2));

However, to perform the insert and update operations in the database, executeUpdate() method is used
which returns the boolean value to indicate the successful completion of the operation.

Closing connection: By closing connection, object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Syntax of close() method is given below.

public void close()throws SQLException

Consider the following example to close the connection.

con.close();

40. What are the JDBC API components?

Answer:

Connection: The Connection object is created by using getConnection() method of DriverManager class.
DriverManager is the factory for connection.

Statement: The Statement object is created by using createStatement() method of Connection class. The
Connection interface is the factory for Statement.

PreparedStatement: The PrepareStatement object is created by using prepareStatement() method of


Connection class. It is used to execute the parameterized query.

ResultSet: The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
before the first row. The executeQuery() method of Statement interface returns the ResultSet object.

ResultSetMetaData: The object of ResultSetMetaData interface cotains the information about the data
(table) such as numer of columns, column name, column type, etc. The getMetaData() method of
ResultSet returns the object of ResultSetMetaData.

DatabaseMetaData: DatabaseMetaData interface provides methods to get metadata of a database such as


the database product name, database product version, driver name, name of the total number of tables, the
name of the total number of views, etc. The getMetaData() method of Connection interface returns the
object of DatabaseMetaData.

CallableStatement: CallableStatement interface is used to call the stored procedures and functions. We
can have business logic on the database through the use of stored procedures and functions that will make
the performance better because these are precompiled. The prepareCall() method of Connection interface
returns the instance of CallableStatement.

Classes:

DriverManager: The DriverManager class acts as an interface between the user and drivers. It keeps
track of the drivers that are available and handles establishing a connection between a database and the
appropriate driver. It contains several methods to keep the interaction between the user and drivers.

Blob: Blob stands for the binary large object. It represents a collection of binary data stored as a single
entity in the database management system.

Clob: Clob stands for Character large object. It is a data type that is used by various database
management systems to store character files. It is similar to Blob except for the difference that BLOB
represent binary data such as images, audio and video files, etc. whereas Clob represents character stream
data such as character files, etc.

SQLException It is an Exception class which provides information on database access errors.

41. What are the JDBC statements?


Answer: In JDBC, Statements are used to send SQL commands to the database and receive data from the
database. There are various methods provided by JDBC statements such as execute(), executeUpdate(),
executeQuery, etc. which helps you to interact with the database.

There is three type of JDBC statements given in the following table.

Statements Explanation

Statement Statement is the factory for resultset. It is used for general purpose access to
the database. It executes a static SQL query at runtime.

PreparedStatement The PreparedStatement is used when we need to provide input parameters to


the query at runtime.

CallableStatement CallableStatement is used when we need to access the database stored


procedures. It can also accept runtime parameters.

42. What is a Servlet?

Answer: A Servlet is a Java program that runs on a Web server. It is similar to an applet but is processed
on the server rather than a client‟s machine. Servlets are often run when the user clicks a link, submits a
form, or performs another type of action on a website

43. What is a Cookie?

Answer: A cookie is a piece of information that is present between 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.

44. How PrintWriter is different from ServletOutputStream?

Answer: PrintWriter is basically a character-stream class. On the other hand, ServletOutputStream is a


byte-stream class. The PrintWriter class can be used to write only character-based information whereas
ServletOutputStream class can be used to write primitive values as well as character-based information.

45. Explain is servlet mapping?

Answer: Servlet mapping is a process of defining an association between a URL pattern and a servlet.
The mapping is used to map requests to Servlets.

46. What are the annotations used in Servlet?

Answer: The important 3 annotations used in the servlets are.

@WebServlet : for servlet class.

@WebListener : for listener class.

@WebFilter : for filter class.

47. What is the difference between a Generic Servlet and HTTP Servlet?

Answer: A common feature between Generic Servlet and HTTP Servlet is both these Classes are
Abstract Classes. But, they do have differences between them which discussed as follows

Generic Servlet HTTP Servlet


Protocol Independent Protocol Specific

Belongs to javax.servlet package Belongs to javax.servlet.http package

supports only service() method supports doGet(), doPost(), doHead() methods

48. What is the use of RequestDispatcher Interface?

Answer: The RequestDispatcher interface defines the object that receives the request from the client and
dispatches it to the resources such as a servlet, JSP, HTML file. The RequestDispatcher interface has the
following two methods:

1. public void forward(ServletRequest request, ServletResponse response)

Forwards request from one servlet to another resource like servlet, JSP, HTML etc.

2. public void include(ServletRequest request, ServletResponse response)

Includes the content of the resource such as a servlet, JSP, and HTML in the response.

49. Can a JSP be called using a Servlet?

Answer: Yes, Servlet can call a JSP using RequestDispatcher interface.

Example:

RequestDispatcher reqdis=request.getRequestDispatcher("log.jsp");

reqdis.forward(request,response);

50. Explain the Servlet Filter.

Answer: A Filter is defined as a pluggable object that is invoked either at the pre-processing or post-
processing of a request.

51. Why do we need Servlet Filter?

Answer: We need Servlet Filters for the following reasons:

Logging the request parameters to log files.

Authentication and Authorization of the request for the needed resources.

Formatting of the request body/header before sending it to the servlet.

Compressing response data sent to the client.

Change the response by adding some cookies and header information.

52. Write a Hello World Program using Servlets.

Answer: The code to write a Hello World PRogram using Servlets is as follows:

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {

message = "Hello World";

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<h1>" + message + "</h1>");

public void destroy() {

53. What is the difference between ServletConfig and ServletContext?

Answer: Some of the major differences between ServletConfig and ServletContext are:

ServletConfig ServletContext

ServletConfig is a unique object per servlet. ServletContext is a unique object for a complete
application.

ServletConfig is used to provide the ServletContext is used to provide the application-level

init parameters to the servlet. init parameters that all other servlets can use.

Attributes in the ServletConfig object We can set the attributes in ServletContext

cannot be set. that other servlets can use.

Syntax for ServletConfig: Syntax for ServletContext:

public ServletConfig getServletConfig(); public ServletContext getServletContext();

Example of ServletConfig: Example for ServletContext:

ServletConfig config=getServletConfig(); ServletContext application=getServletContext();

54. What is the use of HttpServletRequestWrapper and HttpServletResponseWrapper?

Answer: Both HttpServletRequestWrapper and HttpServletResponseWrapper classes are used to help


developers with a custom implementation of a servlet request and response types. Programmers can
extend these classes and override only the specific methods that they need to implement for customized
request and response objects.

55. Write a simple Servlet program to print the contents of HTML.

Answer: We can print the contents of HTML using the following steps:

Step 1: Get the object of PrintWriter using request.

PrintWriter out = response.getWriter();

Step 2: Now print HTML.

out.println("Hello World");

56. What do you mean by InterServlet communication?

Answer: InterServlet communication is a method to invoke another servlet using


RequestDispatcherforward() and include() methods and provide additional attributes in the request for
other servlet use.

57. What is JSP?

Answer: Java Server Pages (JSP) technology is the Java platform technology for delivering dynamic
content to web clients in a portable, secure, and well-defined way. The Java Server Pages specification
extends the Java Servlet API to supply web application developers with a strong framework for creating
dynamic web pages on the server using HTML, and XML templates, and Java code, which is secure, fast,
and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet
semantics. JSP has become the well-liked request handler and response mechanism. Although JSP
technology goes to be a strong successor to basic Servlets, they need an evolutionary relationship and
may be utilized in a cooperative and complementary manner.

58. Explain the benefits of JSP?

Answer: JSP pages are faster because they are pre-compiled.

It is flexibles as it‟s part of the Sun‟s J2EE and can be used with other types of Java technologies, such as
Servlet.

It is a „fly by night‟ technology as multiple vendors support it because of its specifications.

It is easy to develop because HTML can be easily maintained with JSP. Relatively minimal programming
skills required.

JSP page code is not visible to the client, only generated HTML is visible.

It is easy to read, write, and maintain JSP pages.

It is easy to extend the JSP language by using pluggable, reusable tag libraries available.

59. What is a JSP page?

Answer: A JSP page is a text-based document that contains two types of text: static template data, which
can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements,
which construct dynamic content.
60. Is JSP technology extensible?

Answer: YES, JSP technology is extensible through the development of custom actions, or tags, which
are encapsulated in tag libraries.

61. What is Hibernate Framework?

Answer: Hibernate is an open-source ORM framework that is used to map Java classes to database
tables. It provides a high-level abstraction for database programming and makes it easier for developers to
interact with the database.

Hibernate provides a set of APIs for performing CRUD operations and allows developers to write
database queries in a platform-independent manner. To install the latest version of Hibernate Framework,
follow this page.

62. What are the benefits of using Hibernate Framework?

Answer: Simplifies database programming

Reduces development time

Provides a layer of abstraction between the application and the database

Improves performance by providing efficient database access

Supports caching and lazy loading

Provides a platform-independent way of writing database queries

63. What is Object-Relational Mapping (ORM)?

Answer: ORM is a programming technique that allows developers to map object-oriented programming
concepts to relational databases. ORM frameworks like Hibernate provide a set of APIs that allow
developers to interact with the database in an object-oriented manner.

Hibernate-Interview-Questions

1. What is the difference between Hibernate and JDBC?

Answer: Hibernate is a high-level ORM framework that provides a set of APIs for performing database
operations. JDBC is a low-level API that allows developers to interact with the database directly.
Hibernate provides a layer of abstraction between the application and the database, whereas JDBC
requires developers to write SQL queries to interact with the database.

2. What is a Session in Hibernate?

Answer: A Session is a lightweight object that is used to interact with the database in Hibernate. It
provides a set of APIs for performing CRUD operations, and developers can use it to perform database
transactions.

3. What is a Transaction in Hibernate?

Answer: A Transaction is a set of database operations that are performed as a single unit of work. In
Hibernate, developers can use transactions to ensure that all database operations are performed
successfully or rolled back in case of any error.
4. What is Hibernate caching?

Answer: Hibernate caching is a mechanism that allows Hibernate to store frequently accessed data in
memory for faster access. Hibernate supports two types of caching: first-level caching and second-level
caching.

5. What is the difference between first-level and second-level caching in Hibernate?

Answer: First-level caching is a Hibernate-specific cache that stores objects in the Session object. It is
enabled by default and is only valid for a single Session. Second-level caching is a cache that is shared by
multiple Sessions and is used to store frequently accessed data for faster access.

Heading for a Java Interview? Read this quick refresher for most-often asked Java Interview
Questions.

6. What is lazy loading in Hibernate?

Answer: Lazy loading is a technique used by Hibernate to defer the loading of related entities until they
are actually needed. This can improve performance by reducing the number of database queries required
to load an object.

7. What is the difference between eager loading and lazy loading in Hibernate?

Answer: Eager loading is the default behaviour in Hibernate, where all related entities are loaded at once.
Lazy loading, on the other hand, defers the loading of related entities until they are actually needed.

8. What is HQL (Hibernate Query Language)?

Answer: HQL is a Hibernate-specific query language that is used to write database queries in a platform-
independent manner. It is similar to SQL, but instead of writing SQL queries, developers write HQL
queries that are translated to SQL queries by Hibernate.

9. What is the difference between HQL and SQL?

Answer: HQL (Hibernate Query Language) and SQL (Structured Query Language) are both used to
query data from a database. However, there are several differences between the two. Here are some of the
main differences:

Object-oriented vs. Relational: HQL is an object-oriented query language, while SQL is a relational query
language. HQL queries are written in terms of objects and their properties, whereas SQL queries are
written in terms of tables and columns.

Syntax: The syntax of HQL is similar to SQL but with some differences. For example, in HQL, we use
the name of the Java class instead of the name of the database table. We also use object properties instead
of column names.

Portability: HQL is more portable than SQL because it is not tied to any specific database. HQL queries
can be executed on any database supported by Hibernate, whereas SQL queries can only be executed on
the specific database for which they were written.

Database-specific functions: SQL allows the use of database-specific functions and features, whereas
HQL does not. HQL is designed to work with any database, so it only supports functions that are common
to all databases.
Caching: HQL results can be easily cached by Hibernate, whereas caching SQL queries is more difficult.

Type safety: HQL is type-safe, meaning that it performs compile-time checks on the queries to ensure that
they are valid. SQL is not type-safe, so queries may fail at runtime if they are not valid.

Overall, HQL is more object-oriented and portable, while SQL is more database-specific and powerful.
Which one to use depends on the requirements of the application and the preferences of the developer.

10. What is the purpose of the Hibernate Configuration file?

Answer: The Hibernate Configuration file is used to configure the Hibernate framework. It contains
information about the database connection, mapping files, cache settings, and other configuration
parameters

64. What is Spring Boot and what are its Benefits?

Answer: Spring Boot represents a fusion of the lightweight Spring application framework, configuration
annotations, and embedded HTTP server.

Made available with an auto-configuration feature, and support for Spring Initializer, Groovy, and Java,
Spring Boot reduces Integration Test, Development, and Unit Test time.

It aids the development of fast, responsive, and secure web applications, providing users with a complete
configuration and programming model for Java enterprise applications.

Spring Boot, utilizing the core features of the Spring application framework, offers a faster development
technique for RESTful or REST architecture-based web services.

65. What makes Spring Boot superior to JAX-RS?

Answer: By leveraging Spring Boot features, users can experience significant advantages over JAX-RS,
including:

Fast deployment

High scalability

Container compatibility

Minimal configuration

Lower production time

Increased productivity

Reduced development time

Easy monitoring and management of applications

66. What Spring Boot features help develop Microservices Applications?

Answer: Primarily used for developing microservices-based applications, Spring Boot offers the
following key features for configuring, developing, and deploying microservices architecture.

Integrates a tool called the Actuator, which enables users to manage and monitor applications

Provides support for embedded servers, such as Jetty and Tomcat


Users can simply run war files, without deploying it

Includes an Auto-Configuration functionality, allowing users to configure Spring applications


automatically

Supports HTTP client Feign

67. Why Spring Boot is preferred over any other framework?

Answer: The Spring cloud that comes with Spring Boot, includes vast libraries, which is one of the major
reasons why most developers prefer the Java-based Spring Boot. In addition, Spring Boot offers superior
compatibility with Spring frameworks, and it also provides excellent support for docker containerization,
heightening performance, and useability. Some of the most compelling reasons for using Spring Boot
include:

Provides the best means to configure Java beans

Offers robust batch processing

Helps users effectively manage Representational State Transfer (REST) endpoints

Integrates an auto-configuration tool, eliminating the need for manual configuration

Enables annotation-based configurations

Ease of dependency management

Includes embedded servlet containers

68. What are the key dependencies of Spring Boot?

Answer: Mentioned below are important Spring Boot dependencies that need to be added to a Gradle-
based or Maven-based application, to ensure application compatibility with Spring Boot features.

spring-boot-starter-parent

spring-boot-maven-plugin

spring-boot-starter-test

spring-boot-starter-security

spring-boot-starter-actuator

Spring-boot-starter-web

69. What are the advantages of Spring Boot?

Answer: The advantages of Spring Boot are as follows:

It is very simple to create Spring-based apps in Java or Groovy.

It cuts down on development time and also increases the output.

It eliminates the requirement to write repetitive code, annotations, and XML configuration.
It is very simple to combine Spring Boot Application with its Spring Ecosystem, which includes Spring
JDBC, Spring ORM, Spring Data, and Spring Security, among other things.

To minimize developer effort, it employs the "Opinionated Defaults Configuration" approach.

It provides Embedded HTTP servers such as Tomcat, Jetty, and others to help us build and test our web
applications quickly.

LONG ANSWER TYPE

1. what is use of JDBC Thin Driver?


2. Write the declaration tag of JSP?
3. What is the method can be used to get the value of "form" tag parameter to servlet?
4. What is the purpose of the Spring MVC module?
5. Explain the steps involved in establishing a database connection using JDBC and provide a code
example for each step
6. Explain the difference between JSP directives, JSP scripting elements, and JSP standard actions.
Provide examples of when to use each of these elements in a JSP page.
7. Explain the difference between HttpServletRequest and HttpServletResponse objects in Servlets.
Provide examples of when each object is commonly used.
8. Explain the Spring MVC (Model-View-Controller) architecture. Describe the roles of each
component and provide an example scenario where Spring MVC is used.
9. Discuss the advantages and disadvantages of using Hibernate in a project.
10. Describe the steps involved in establishing a database connection using JDBC.
11. Discuss the Spring MVC architecture and the role of the DispatcherServlet
12. What is Spring Boot, and how does it simplify the development of Spring-based applications
13. Explain the Object-Relational Mapping (ORM) concept and how Hibernate implements it.
14. Describe the benefits of using Spring's Inversion of Control (IoC) container in Java applications.
15. Explain the difference between the doGet and doPost methods in a servlet. Provide examples of when
you would use each method with syntax of each method.
16. What is the Spring Framework, and what are its core features?
17. Explain the difference between a JDBC ResultSet and a JDBC PreparedStatement.
18. Describe the life cycle of a JSP page. What are the different phases involved explain them in brief.
19. Discuss the advantages and disadvantages of using Hibernate as an ORM framework compared to
traditional JDBC.
20. Explain the steps involved in establishing a JDBC connection to a relational database. Discuss the role
of DriverManager and Connection interfaces in this process.
21. Explain the lifecycle of a servlet in Java. Discuss each phase and the purpose it serves in the servlet's
execution.(7)
22. Explain Hibernate One-to-One Relationship with required code.(7)
23. Create a Servlet that performs user authentication. The Servlet should receive a username and
password from a form, compare it with predefined credentials, and redirect the user to a success page
if the credentials are correct. If the credentials are wrong, display an error message.(7)
24. Explain the Core Concepts of Inversion of Control (IoC) in the Spring Framework. How does IoC
promote loose coupling in application design? Provide examples to illustrate your points.(8)
25. Define the concept of a Hibernate Session and explain its lifecycle. What are the best practices for
opening and closing sessions in a Hibernate application?(7)
26. Compare and contrast the advantages and disadvantages of session management techniques in
servlets, such as cookies, URL rewriting, and HttpSession.(7)
27. What are the life-cycle methods for a servlet?with syntax
28. What is autowiring in spring? What are the autowiring modes?
29. What are the steps to connect to the database in java?
30. How is JSP used in the MVC model?
31. Explain JDBC Architecture and Steps to connect JDBC with Program code?
32. Explain Hibernate ?Provide the code to connect Java Application to DataBase.
33. What are the modules of spring framework?with Dependency Injection code
34. Explain ServletCofig? with Syntax and Example
35. Write a servlet code to take User name and Password from the web page and Store the data in
DataBase
36. Explain Hibernate Annotations with the complete code ?
37. What is the difference between BeanFactory and ApplicationContext?
38. Explain the Lifecycle of Servlet?
39. What is Spring IOC Container?
40. What is difference between Statement and PreparedStatement?
41. What scrpting elements & implicity objects in JSP?
42. Write a java program using JDBC API CURD operation for (Ex: Id, Name & Salary) i) Connection to
DB (Oracle/MySQL etc) ii) Create & Insert Data into DB iii) Retrive data from DB iv) Update data in
DB.
43. i) Describe the Architecture of ORM using Hibernate. ii) Expain Mapping annotation of

Hibernate?

44. Explain the flow of execution of Spring MVC Framework?


45. i) What is the difference between GenericServlet and HttpServlet? & ii) Write steps to create
HttpSession for forwarding & getting data from one servlet to another servlets and destroy the session
in servlet?
46. Write a web application program using Servlets i) Wirte UI using HTML for input fileds ii) Get
values into Servlet & Connect to DB using JDBC and Send data to Database. iii) write web.xml
servlet configuration details.
47. Write a program for CURD Operation using Hibernate ORM tool?
48. i) What is dependency injection (DI)? What are the types of DI? ii) What is a Spring Application
Context? What are some example usages of one?

Additional Important Questions:

1. What is Spring MVC ? Explain advantages of Spring MVC ? Explain life cycle of web request.
2. What are the differences between executeQuery() and executeUpdate()?

3. What are the important JPA annotations used for hibernate mapping ? Give an example to implements
annotations in hibernate application.

4. What are the different types of JDBC drivers in Java?

5. Difference Between include Directive and include Action of JSP?

6. What are the implicit Objects in JSP? Explain any two objects with an example.

7. What is state management ? Explain cookie and session techniques with an example
8. What is web deployment descriptor file ? Explain with an example

9. What are the different types of RowSet objects?

10. What is RequestDispatcher? Explain forward() and include() method with an example.

11. What is Hibernate Framework ? Explain types of Hibernate Persistence object in details.

12. What is the difference between the transient, persistent, and detached state in Hibernate?

13. What are the differences between Statement and PreparedStatement Interface ?

14. What is the differences between the save() and persist() method in Hibernate?

15. What are the types of statements in JDBC ? Explain each one of types with an example.

16. What is the difference between BeanFactory and ApplicationContext ? Give an example to implement
Bean factory and ApplicationContext.

17. Explain methods init(), service(), destroy() with code.

18. What is the role of DispatcherServlet in Spring MVC?

19. What is Entity relation ? Explain types of relation in hibernate ? Give an example of any one of the
types of relation.

20. What is Hibernate Query Language (HQL)?

21. What is the difference between Session and SessionFactory in Hibernate?

22. What is Spring Framework ? Explain the core modules of Spring framework ? What are the steps of
the Bean Lifecycle ?

23. What are the joint Point and point cut?

24. What is the difference between @Controller and @RestController in Spring MVC?

IMPORTANT LINK:

Read more: https://javarevisited.blogspot.com/2011/09/spring-interview-questions

answers-j2ee.html#ixzz8EubZtLqW

You might also like