JDBC INTERVIEW QUESTION
1) What is JDBC?
o JDBC stands for Java Database Connectivity which help us to connect java with
RDBMS Application
o Using jdbc we can make java to interact with Database
o Jdbc is Standard API
o It is present in [Link].*
2)What is JDBC Driver?
o It is an additional software component given by database vender in the form of jar
files
o Driver are database dependent which means depending on RDBMS application
drivers will change
3)What are the steps to connect to the database in java?
o Load and register Driver
o Establish connection
o Create Statement
o Execute Query
o Close the connection
4) What are the JDBC statements?
o Statement is used to carry sql Query from java to database
o There are three types of statement
Statement (Is used to carry static Query)
PreparedStatement(Is used to carry dynamic Query)
CallableStatement(Is user to carry PLSQL statements)
5) What are the differences between Statement and PreparedStatement
interface?
6) What are the differences between execute, executeQuery, and
executeUpdate ?
The important methods of Statement interface are as follows:
o public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns
the object of ResultSet.
o public int executeUpdate(String sql): is used to execute specified query, it may be
create, drop, insert, update, delete etc.
o public boolean execute(String sql): is used to execute queries that may return
multiple results.
o public int[] executeBatch(): is used to execute batch of commands.
7) What is ResultSet?
o The [Link] interface represents the data base result set, which is obtained
after the execution of SQL query using Statement objects.
ResultSet rs = [Link](sqlQuery);
o Object of ResultSet maintains a cursor pointing to the current row of data in the result
set. Initially, the cursor is located before the first row. Then the cursor is moved to the
next row by using the next() method.
syntax : public boolean next(){ }
o the above method return true if the next record is present else it will return false
if the record are present in the resultset get the data using data using getter
methods present in resultSet object
public int getInt(int columnposition) throws sqlException{ }
public String getString(int columnposition) throws sqlException{}
public long getLong(int columnposition) throws sqlException{}
public double getDouble(int columnposition) throws sqlException{}
8) What is DriverManager in JDBC?
o JDBC DriverManager is used to manage the set of JDBC drivers that are available for
an application to use.
o Multiple JDBC drivers can be used concurrently by an application, if necessary. By
using a Uniform Resource Locator(URL), each application specifies a JDBC driver.
o When we load the JDBC Driver class into an application, it register itself to the
DriverManager by using [Link]() or [Link]().
o To check this, you can have a look into the source code of JDBC Driver classes. After
this, when we call [Link]() method by passing the details
regarding database configuration, DriverManager will make use of registered drivers
to obtain the connection and return it to the caller program.
9)What is JDBC Connection?
o A connection is an Interface that includes all methods for contacting a database. The
connection object is a source of communication .
10) Explain Batch Processing ?
o Executing multiple Query in Single Trancation is called as Batch Processing
o Methods Used in batch Processing
addBatch() -> Used to add Statement into batch
executeBatch() -> User to execute Batch
clearBatch() -> Used to clear batch
11) What are the main components of JDBC?
Driver Manager: Manages database drivers.
Driver: Establishes a connection with the database.
Connection: Represents a session with the database.
Statement: Executes SQL queries.
ResultSet: Holds data retrieved from the database.
12) What are common exceptions in JDBC?
SQLException: Generic database error.
SQLTimeoutException: Timeout occurred.
SQLIntegrityConstraintViolationException: Constraint violations.
Hibernate Interview Questions For Freshers
1. What is Hibernate?
o Hibernate is a Java framework that simplifies the development of Java
applicationon to interact with the database. It is an open source, lightweight, ORM (Object
Relational Mapping) tool.
o Hibernate implements the specifications of JPA (Java Persistence API) for data persistence
2. Advantages of using Hibernate?
o Open Source and Lightweight
o Fast Performance
o Database Independent Query
o Automatic Table Creation
o Simplifies Complex JoiN
3. What is ORM in Hibernate?
An ORM tool simplifies the data creation, data manipulation and data access. It is a programming
technique that maps the object as one row in the table in the database
4. What is Java Persistence API (JPA)?
o Java Persistence API (JPA) is a Java specification that provides certain functionality and
standard to ORM tools.
o The [Link] package contains the JPA classes and interfaces
5. What are the advantages of Hibernate over JDBC?
o Object-Relational Mapping (ORM)
o Automatic SQL Generation
o Hibernate Query Language (HQL)
o Transaction Management
o Caching
o Lazy Loading
o Database Independence
o Declarative Fetching Strategies
o Batch Processing
o Automatic Table Creation
6). What is JPQL?
o Java Persistence Query Language (JPQL) is a platform-independent object-oriented query
language defined as part of the Java Persistence API (JPA) specification. JPQL is used to make
queries against entities stored in a relational database. JPQL is inspired by SQL.
o JPQL is object-oriented. In JPQL we work with entities and collection of entities, while in SQL
we work with columns and rows
6. What is a EntityManager in Hibernate?
o The EntityManager provides an abstraction over database operations, allowing developers to
perform CRUD (Create, Read, Update, Delete) operations and manage persistent entities in a
consistent manner.
CRUD Operations:
Persist: Save a new entity to the database.
Merge: Update an existing entity.
Remove: Delete an entity from the database.
Find: Retrieve an entity by its primary key.
7) . What is a EntityManagerFactory in Hibernate?
o An entity manager factory provides entity manager instances, all instances
are configured to connect to the same database, to use the same default
settings as defined by the particular implementation, etc
8) What is a EntityTransaction in Hibernate?
o The EntityTransaction interface is used to control resource transactions on
resource-local entity managers
IMPORTANT METHODS :
begin() method - This method is used to start the transaction.
commit() method - This method is used to commit the transaction.
9) Explain the different fetch types in JPA.
o When working with an ORM, data fetching/loading can be classified into two types: eager and
lazy.
o In this quick tutorial, we are going to point out differences and show how we can use these in
Hibernate.
Two types :
o [Link]
o [Link]
10) Explain @Entity
@Entity annotation. This annotation, part of the javax. persistence package, is used at the
class level and marks the class as a persistent entity
11) Explain @Id
@Id is used to specify primary key of the entity in database .
12) What is the difference between merge() and persist() in JPA?
13) What is the difference between @JoinColumn and @JoinTable
annotations?
o Use @JoinColumn when the Entities have direct relationship i.e a foreign key between
Entity1 and Entity2.
o Use @JoinTable when you manage the relationship between Entities in another table also
referred to as JoinTable.
14) What is Hibernate caching?Types of Hibernate Caching?
o Hibernate caching improves the performance of the application by pooling the object in the
cache. It is useful when we have to fetch the same data multiple times.
o There are mainly two types of caching:
First Level Cache, and
Second Level Cache
15) what is cascading in hibernate?
o Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity
whenever the state of its relationship owner (superclass) affected. When the relationship
owner (superclass) is saved/ deleted, then the mapped entity associated with it should also
be saved/ deleted automatically.
o When we perform some action on the target entity, the same action will be applied to the
associated entity.
o TYPES OF CASCADING •
All JPA-specific cascade operations are represented by the [Link]
enum containing entries:
ALL
PERSIST
MERGE
REMOVE
REFRESH
DETACH
16) Explain Mapping in hibernate?
@OneToOne Defines a one-to-one relationship.
@OneToMany Defines a one-to-many relationship.
@ManyToOne Defines a many-to-one relationship.
@ManyToMany Defines a many-to-many relationship.
17) Explain the difference between JDBC and Hibernate.
JDBC is a low-level API requiring manual query writing and result mapping, while
Hibernate is an ORM tool that abstracts database interactions and uses object-
oriented programming.
18) What are the key differences between JPA and Hibernate?
JPA is a specification, while Hibernate is an implementation of JPA.
JPA uses annotations and interfaces defined by the specification, whereas Hibernate
offers additional features like Criteria API and caching.
19)What are the different states of an entity in Hibernate/JPA?
Transient: Newly created object, not associated with a database.
Persistent: Object associated with a Hibernate session or EntityManager.
Detached: Object disconnected from Hibernate session but still represents database
data.
Servlet and Jsp interview Question
1)What is a Servlet?
o Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page)
o Servlet technology is robust and scalable because of java language.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including documentation
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page
2) What is the life cycle of a Servlet?
o The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
Servlet class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy method is invoked.
3) what is web container?
o A web container is the component of a web server that interacts with the java servlet.
o A web container manages the life cycle of servlets and it maps a URL to a particular servlet
while ensuring that the requester has relevant access rights.
o Java servlet do not have main method, so a container is required to load them. The servlet
gets deployed on the web container
4)what is different between GenericServlet and httpServlet ?
4) What is the difference between config and context?
5) What is servlet chaining?
o Taking the request from a browser window and processing that request by using multiple
servlets as a chain is called servlet chaining
6) What is the purpose of the RequestDispatcher interface?
o The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp.
o This interface can also be used to include the content of another resource also. It is one of the
way of servlet collaboration.
7) What is the difference between forward() and sendRedirect() methods?
o The forward() method is part of the RequestDispatcher class, and it allows the request to
be forwarded from one servlet or JSP to another resource on the server.
o he sendRedirect() method is part of the HttpServletResponse class, and it sends an
HTTP response to the client, instructing it to make a new request to a different resource (URL).
8) what do u mean by session and session tracking techniques?
o session simply means a particular interval of time.
o Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Session Tracking Techniques
There are four techniques used in Session tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
9) Explain Cookies in Servlet .
o A cookie is a small piece of information that is persisted between the multiple client requests.
o 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
10) What is the difference between session and cookie?
11) What is a deployment descriptor?
o The deployment descriptor is the file used by the servlet container to define which
servlets match up with which URLs. It also defines which servlet or resource provides the
landing page for the root of the service.
o [Link] is Deployment Descriptor.
12) what is jsp?
o stands for Java Server Page
o It is an advanced version of Servlets
o We will be inserting Java code into html page
o JSP is first converted into servlets by JSP container before processing the client’s request.
o In MVC architecture JSP will act as View layer
13) what is jsp lifecycyle?
o Translation of JSP page to Servlet
o Compilation of JSP page(Compilation of JSP into [Link])
o Classloading ([Link] to [Link])
o Instantiation(Object of the generated Servlet is created)
o Initialization(jspInit() method is invoked by the container)
o Request processing(_jspService()is invoked by the container)
o JSP Cleanup (jspDestroy() method is invoked by the container)
14) Explain 9 implicit object in Jsp?
o request - This is the HttpServletRequest object associated with the request.
o response - This is the HttpServletResponse object associated with the response to the
client.
o out - This is the PrintWriter object used to send output to the client.
o session -This is the HttpSession object associated with the request.
o application - This is the ServletContext object associated with the application context.
o config - This is the ServletConfig object associated with the page.
o pageContext - This encapsulates use of server-specific features like higher
performance JspWriters.
o page - This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
o Exception - The Exception object allows the exception data to be accessed by
designated JSP.
15)Explain different between Servlet and Jsp?
16) Explain Jsp Tags
o script let tag: <% code %>
used to write Java codes into JSP
o expression tag: <% = printing statement %>
used to print the values
o Declaration tag: <%! code %>
used for declaration purposes
17)What is the difference between doGet() and doPost() in servlets?
doGet() is used for requests with parameters appended in the URL. It is limited by
the URL length.
doPost() is used for sending large amounts of data, including form data, in the
request body.
18) What is the purpose of the [Link] file?
It is the deployment descriptor file used to configure servlets, JSPs, filters, and other
components in a web application.
19) What is the difference between ServletConfig and ServletContext?
o ServletConfig: Provides configuration parameters for a specific servlet.
o ServletContext: Shared object across the whole application for global
initialization parameters.
Spring interview Question
1) What is Spring?
o the Spring Framework is an open-source Light weight framework for
o building enterprise Java application
o It was developed by Rod Johnson in 2003.
o Spring framework makes the easy development of JavaEE application.
o It is also called as frameworks of frameWorks because it provides support for framework
like EJB,HIBERNATE,STRUTS
o Spring is a Dependency Injection and Inversion of Control(IOC) frame work
o With the help of spring we can develop loosely coupled application
2) What are the advantages of spring framework?
o Predefined Templates
o Loose Coupling
o Easy to test
o Lightweight
o Fast Development
o Powerful Abstraction
3) What is IOC ?
o IOC stands for inversion of control
o the process of transfering the controller of creating object and injecting object to the spring
frame work
o IOC makes the code loosely coupled
4) What is Di ?
o DI Stands for Dependency Injection
o Dependency Injection (DI) is a design pattern to achieve or implement inversion of controller
o (Or) The process of injecting(setting) Values for Dependency is called As Dependency
Injection
5) What is spring container (IOC – container)?
o Spring Container is responsible for managing the lifecycle of an object(bean) Spring
Spring Container does the following task
o Create an object
o Stores the object in the memory
o Manages the object(injecting object into another object)
The Spring container is refered as
o Bean Factory (xml)
o Application Context which is predefined interface (Annoataion)
The important implementation class of application Context
o ClassPathXmlApplicationContext("[Link]");
o fileSystemXmlApplicationContext
o WebApplicationContext
o AnnotationConfigApplicationContext
6) What is the difference between constructor injection and setter injection?
constructor injection
constructor injection is generally recommended for mandatory
dependencies to ensure object integrity.
setter injection
When dependencies are optional or may need to be reconfigured after object
creation.
7)Explain Bean life cycle in Spring?
o spring lifecycle is managed by spring container'
o Spring container is the core of the spring framework
o Spring container will get executed when we run the program
o Spring container will create instance per request
o Spring will inject the dependencies
Init-method
o it is used to initialize bean object
o Init () is called after injecting the dependencies by spring container
Destroy-method
o it is used to destroy bean object
o Destroy () is called before closing the JVM
8)What are the different types of Spring Bean scopes?
o Singleton (default): One instance per Spring IoC container.
o Prototype: A new instance is created each time the bean is requested.
o Request: Scoped to an HTTP request (used in web apps).
o Session: Scoped to an HTTP session (used in web apps).
o Global-session: Scoped to a global HTTP session (rarely used).
9) Explain annotation
@component,@AutoWired,@Qualifier,@configuration,@bean,@primary,@c
omponentScan
@Component
o it is class level annotation which is used to create object of the class
o A class which is assigned with component annotation is called componenet class
@Configuration
o is a class-level annotation indicating that an object is a source of bean definitions.
@ComponentScan
o annotation along with the @Configuration annotation to specify the packages that we want
to be scanned.
o @ComponentScan without arguments tells Spring to scan the current package and all of its
sub-packages
@value
it is data member level annotation which is used to inject primitive datatype and String
@autowired
o it is data member level annotation which is used to identify particular dependency as a
referance type of dependency and it is used to inject the object of same class or
Implementation class
@qualifier
o It is data member level annotation which is used to carry the object of particular
Implementation class
@Bean
o The @Bean annotation is used to indicate that a method returns object to be managed by
the Spring IoC container.
@Primary
o indicates that a particular bean should be given preference when multiple
beans are candidates to be autowired to a single-valued dependency.
10) What are the different ways to configure beans in Spring?
XML-based configuration ([Link])
Annotation-based configuration (@Component, @Autowired, @Bean)
Java-based configuration (@Configuration, @Bean)
11)What is a Spring Bean?
A Spring Bean is an object that is instantiated, managed, and configured by the
Spring IoC container.
12)What is the difference between @Bean and @Component?
@Bean: Used in Java-based configuration to explicitly define a bean.
@Component: Used to mark a class as a Spring-managed component. It is detected
during classpath scanning.
Spring Boot Interview Questions
1)WHAT IS SPRING BOOT?
Java Spring Boot (Spring Boot) is a tool that makes developing web application and
microservices with Spring Framework faster and easier through three core
capabilities:
[Link]
[Link] opinionated approach to configuration
[Link] ability to create standalone applications
These features work together to provide you with a tool that allows you to set up a
Spring-based application with minimal configuration and setup.
2. What are the Features of Spring Boot?
o You can choose Spring Boot because of the features and benefits it offers as given here −
o It provides a flexible way to configure Java Beans, XML configurations, and Database
Transactions.
o It provides a powerful batch processing and manages REST endpoints.
o In Spring Boot, everything is auto configured; no manual configurations are needed.
o It offers annotation-based spring application
o Eases dependency management
o It includes Embedded Servlet Container
[Link] is different between Spring Boot and Spring?
4) What are the Spring Boot Starter Dependencies?
o Spring Boot provides a number of starters that allow us to add jars in the classpath. Spring
Boot built-in starters make development easier and rapid. Spring Boot Starters are the
dependency descriptors.
[Link] @SpringBootApplication annotation
o The @SpringBootApplication annotation is a combination of
@EnablAutoConfiguration,@Configuration, and @ComponentScan.
6) explain @EnableAutoConfiguration
o @EnablAutoConfiguration: Because of this feature, the application automatically produces
and registers bean methods depending on both the jar files on the included classpath and the
beans we define.
7)Explain Annotation
o @Service This is an alternative to @Component that specifies you intend to
use the class as part of your service layer. However, it doesn’t actually implement anything
differently than @Component.
o @Controller is a specialized @Component marked as a controller in MVC architecture.
o @Repository This annotation marks a class as part of your data layer, for handling storage,
retrieval, and search..
o @RestController combines the @Controller and @ResponseBody into a single annotation.
@RestController classes return domains instead of views.
o @PostMapping It maps the HTTP POST requests on the specific handler method. It is used
to create a web service endpoint that persist data into database.
o @GetMapping It maps the HTTP GET requests on the specific handler method. It is used to
create a web service endpoint that fetches data from database.
o @PutMapping It maps the HTTP PUT requests on the specific handler method. It is used to
create a web service endpoint that creates or updates data.
o @DeleteMapping It maps the HTTP DELETE requests on the specific handler method. It is
used to create a web service endpoint that deletes a resource
o @RequestBody It is used to bind HTTP request with an object in a method parameter.
Internally it uses HTTP MessageConverters to convert the body of the request. When we
annotate a method parameter with @RequestBody, the Spring framework binds the
incoming HTTP request body to that parameter.(From Json Body)
o @RequestParam It is used to extract the query parameters form the URL. It is also known as
a query parameter. It is most suitable for web applications. It can specify default values if
the query parameter is not present in the URL.
o @PathVariable It is used to extract the values from the URI. It is most suitable for the
RESTful web service, where the URL contains a path variable. We can define multiple
@PathVariable in a method
10) How does Spring handle transactions?
Through declarative (@Transactional) and programmatic transaction management.
11) How do you handle exceptions in Spring?
Use @ControllerAdvice and @ExceptionHandler annotations for global and
method-level exception handling.