Spring Boot Interview Questions for Freshers
1. What is Spring Boot?
Answer:
"Spring Boot is a framework built on top of Spring that is used
to create production-ready, standalone applications quickly. It
provides auto-configuration, starter dependencies,
embedded servers, and monitoring features to simplify
development, especially for microservices and RESTful APIs."
2. What are the Features of Spring Boot?
Or ) What are the advantages of using Spring Boot?
Less-configuration and No XML configuration
Auto-configuration - automatically configures
dependencies by
using @EnableAutoconfiguration annotation and
reduces boilerplate code
Spring Boot Starter POM – To simplify dependencies
Configuration
Exp:Web-starter,JPA Starter,Security Starter,Mail Starter
Spring Boot CLI (Command Line Interface) – generally
for managing dependencies, creating projects and
running the applications.
Actuator – production ready features
Embedded Servers - Spring Boot contains embedded
servers like Tomcat and Jetty for quick application run.
No need of external servers.
4. Define the Key Components of Spring Boot.
The key components of Spring Boot are listed below:
Spring Boot starters
Auto-configuration
Spring Boot Actuator
Spring Boot CLI
Embedded Servers
5. Why do we prefer Spring Boot over Spring?
"We prefer Spring Boot over Spring because it reduces boilerplate
configuration, provides production-ready features, and comes with
embedded servers for faster deployment. Compared to Spring, it is
easier to use, more scalable, faster, and more customizable, making it
ideal for developing modern microservices and RESTful applications."
6. Explain the internal working of Spring Boot.
Or> How does a spring application get started?
Or> “How does Spring Boot work?
"A Spring Boot application starts when the [Link]()
method is called in the main class annotated with
@SpringBootApplication. Internally, Spring Boot:
1. Creates an ApplicationContext to manage beans.
2. Performs component scanning using @ComponentScan to
detect beans, controllers, and services.
3. Applies auto-configuration to automatically configure beans
based on project dependencies.
4. Starts an embedded server (like Tomcat or Jetty) if it’s a web
application.
5. Finally, the application is ready to handle incoming requests
as a standalone, production-ready service."
[Link] are the Spring Boot Starter
Dependencies?
Data JPA starter
Web starter
Security starter
Test Starter
Thymeleaf starter
Mail starter.
9. What does the @SpringBootApplication
annotation do internally?
The @SpringBootApplication annotation combines
three annotations. Those three annotations
are: @Configuration,
@EnableAutoConfiguration, and @ComponentSca
n.
@Configuration: This annotation configures the
beans and packages in the class path.
@EnableAutoConfiguration → Enables Spring Boot’s
auto-configuration mechanism to configure beans
automatically based on classpath dependencies.
@ComponentScan → Scans the current package and
sub-packages for components, beans, controllers, and
services.
So internally, @SpringBootApplication sets up
configuration, auto-configuration, and
component scanning in a single annotation, making
application startup simple."
@SpringBootApplication = @Configuration +
@EnableAutoConfiguration + @ComponentScan
10. What is Spring Initializer?
"Spring Initializer is a web-based tool provided by
Spring that helps us quickly generate the skeleton of a
Spring Boot project. It allows developers to choose
project metadata (like project name, groupId,
artifactId), build tool (Maven/Gradle), dependencies,
and packaging type. Once generated, it provides a
ready-to-use project structure that can be imported
directly into an IDE, saving setup time and effort."
11. What are Spring Boot CLI and the most used
CLI commands?
Spring Boot CLI is a command-line tool that can be
used to create, run, and manage Spring Boot
applications. It is a powerful tool that can help us to
get started with Spring Boot quickly and easily. It is
built on top of the Groovy programming language.
Most used CLI commands are:
spring run → Runs a Spring Boot application.
spring test → Runs tests.
spring jar → Creates an executable JAR file.
spring war → Creates a WAR file.
spring init → Initializes a new Spring Boot project.
spring help → Displays help information for CLI
commands.
Spring Boot Intermediate Interview
Questions
12. What are the basic Spring Boot
Annotations?
@SpringBootApplication → Combines
@Configuration, @EnableAutoConfiguration,
and @ComponentScan.
@RestController → Combines @Controller
and @ResponseBody to create RESTful web
services.
@RequestMapping → Maps HTTP requests
to handler methods (GET, POST, etc.).
@GetMapping, @PostMapping,
@PutMapping, @DeleteMapping →
Specialized request mappings for HTTP
methods.
@Autowired → Injects dependencies
automatically.
@Component, @Service, @Repository →
Marks classes as beans for component
scanning.
@Configuration → Defines configuration
classes that provide bean definitions.
@EnableAutoConfiguration → Enables
auto-configuration of beans based on
classpath settings.
13. What is Spring Boot dependency
management?
Spring Boot dependency
management makes it easier to manage
dependencies in a Spring Boot project. It
makes sure that all necessary dependencies
are appropriate for the current Spring Boot
version and are compatible with it.
14. Is it possible to change the port of
the embedded Tomcat server in Spring
Boot?
"Yes, the embedded Tomcat port can be
changed (default 8080) using [Link] in
[Link] or [Link]."
15. What is the starter dependency of
the Spring boot module?
"Spring Boot starter dependencies are a set
of predefined Maven/Gradle
dependencies that bundle together
commonly used libraries for a specific
feature, so we don’t have to manually search
and configure compatible versions.
For example:
spring-boot-starter-web → For building
web and RESTful applications (includes
Spring MVC, Jackson, Tomcat).
spring-boot-starter-data-jpa → For
working with databases using Spring Data
JPA and Hibernate.
spring-boot-starter-security → For adding
Spring Security features.
spring-boot-starter-test → For testing
(JUnit, Mockito, Spring Test).
16. What is the default port of Tomcat
in spring boot?
The default port of the embedded Tomcat
server in Spring Boot is 8080 . We can
change the default port by setting
the [Link] property in
[Link] file/[Link]
file.
17. Can we disable the default web
server in the Spring Boot application?
"Yes, we can disable the default embedded
web server (like Tomcat) in a Spring Boot
application. This is useful when building
non-web applications, such as batch or
console apps.
The simplest way is to set the server port to
-1 in [Link] or
[Link]
[Link] [Link]
es server:
[Link]=-1
port: -1
Programmatically we can also Disable
Embedded Web Server by using
SpringApplicationBuilder.
18. How to disable a specific auto-
configuration class?
To disable a specific auto-configuration class in a
Spring Boot application, we can use
the @EnableAutoConfiguration annotation
with the " exclude" attribute.
@EnableAutoConfiguration(exclude =
{//classname})
19. Can we create a non-web application in
Spring Boot?
Yes, we can create a non-web application in
Spring Boot. Spring Boot is not just for web
applications. Using Spring Boot, we can create
applications like Microservices, Console
applications, and batch applications.
To do this, we simply disable the embedded web
server by setting [Link]=-1 in
[Link] or using
[Link] programmatically.
20. Describe the flow of HTTPS requests
through the Spring Boot application.
First client makes an HTTP request ( GET, POST, PUT, DELETE ) to the
browser.
After that the request will go to the controller, where all the requests will
be mapped and handled.
After this in Service layer, all the business logic will be performed. It
performs the business logic on the data that is mapped to JPA (Java
Persistence API) using model classes.
In repository layer, all the CRUD operations are being done for the REST
APIs .
A JSP page is returned to the end users if no errors are there.
Flow of HTTP/HTTPS Requests in Spring Boot:
1. Client Request: The client (browser or API client) sends an HTTP/HTTPS
request (GET, POST, PUT, DELETE).
2. DispatcherServlet: Spring Boot’s DispatcherServlet intercepts the
request and acts as the front controller.
3. Controller Layer: DispatcherServlet forwards the request to the
appropriate controller method (@Controller or @RestController) based
on the URL mapping.
4. Service Layer: The service layer executes business logic, which may
involve processing data and calling the repository layer.
5. Repository Layer: The repository/DAO layer interacts with the
database (via JPA or JDBC) to perform CRUD operations.
6. Response Generation: The controller prepares the response, which
could be JSON/XML for REST APIs or a view (JSP/Thymeleaf) for web
applications.
Response to Client: DispatcherServlet sends the final response back to the
client.
Client (Browser/API)
DispatcherServlet (Front Controller)
Controller Layer
Service Layer
Repository Layer (Database)
Response Generation
DispatcherServlet --> Client
21. Explain @RestController annotation in Spring Boot.
@RestController is a specialized annotation in Spring Boot that
combines @Controller and @ResponseBody. It is used to
create RESTful web services and sends data directly to client
without views File
@Controller marks the class as a Spring MVC controller.
@ResponseBody ensures that the return value of controller
methods is sent directly as the HTTP response (like JSON or
XML) instead of rendering a view.
So, with @RestController, you can define API endpoints quickly
without needing to annotate each method with
@ResponseBody."
@RestController = @Controller + @ResponseBody. It’s used to
build REST APIs that return data directly (JSON/XML) Without
views File."
22. Difference between @Controller and @RestController
Note: Both annotations handle requests,
but @RestController prioritizes data
responses for building API.
23. What is the difference between
RequestMapping and GetMapping?
24. What are the differences between
@SpringBootApplication and
@EnableAutoConfiguration annotation?
25. What are Profiles in Spring?
"Spring Profiles allow you to define different
configurations for different environments, like
development, testing, and production.
You can annotate beans or configuration
classes with @Profile("dev"), @Profile("test"),
etc., so they are only active in the specified
environment.
You can activate a profile using the
[Link] property in
[Link], [Link], or via
environment variables/command-line
arguments.
This makes it easy to manage environment-
specific settings like database URLs, credentials,
or feature toggles without changing the main
code."
Explanation:
DevConfig is active only when the dev profile
is active.
ProdConfig is active only when the prod
profile is active.
You can activate a profile in
[Link] like:
26. Mention the differences between WAR
and embedded containers.
Spring Boot Interview Questions For
Experienced
27. What is Spring Boot Actuator?
Spring Boot Actuator is a component of the
Spring Boot framework that provides production-
ready features for monitoring and management
capabilities. We can manage and monitor your
Spring Boot application while it is running.
Note: To use Spring Boot Actuator, we
simply need to add the spring-boot-starter-
actuator dependency to our project.
28. How to enable Actuator in the Spring
boot application?
1. Add Actuator dependency in your
[Link] or [Link]:
2. Configure endpoints (optional)/
Enable endpoints in
[Link] or
[Link].
3. Run the application. You can now
access Actuator endpoints like:
Note: By default, only health and info
endpoints are enabled. You can expose
other endpoints selectively and secure
them for production.
29. What is the purpose of using
@ComponentScan in the class files?
@ComponentScan annotation is used to
tell Spring to scan a package and
automatically detect Spring components,
configurations, and services to configure.
The @ComponentScan annotation can be
used in the following ways:
Without arguments : Scans the package of
the annotated class and its sub-packages.
With basePackageClasses: Specify one or
more classes; Spring scans their packages.
With basePackages: Specify one or more
packages to scan.
30. What are the @RequestMapping and
@RestController annotations in Spring
Boot used for?
@RequestMapping: @RequestMapping is
used to map HTTP requests to handler
methods in your controller classes. It can be
used at the class level and method level. It
supports mapping by:
HTTP method - GET, POST, PUT, DELETE
URL path
URL parameters
Request headers
@RestController is a specialized annotation in Spring
Boot that combines @Controller and @ResponseBody. It
is used to create RESTful web services and sends data
directly to client without views File
@Controller marks the class as a Spring MVC controller.
@ResponseBody ensures that the return value of
controller methods is sent directly as the HTTP response
(like JSON or XML) instead of rendering a view.
31. How to get the list of all the beans in your Spring
boot application?
Using the ApplicationContext object in Spring Boot, we
can retrieve a list of all the beans in our application.
The ApplicationContext is responsible for managing the
beans and their dependencies.
32. Can we check the environment
properties in your Spring boot
application explain how?
"Yes, in Spring Boot, we can access
environment properties using the
Environment object. It allows us to read
configuration values from:
[Link] or
[Link]
Command-line arguments
Environment variables
You can get the Environment instance by
autowiring it or calling getEnvironment()
from the ApplicationContext.
33. How to enable debugging log in the
spring boot application?
a) Ans: Add the logging level property to
[Link].
b) Configure the log pattern to include useful
information.
c) Run the Spring Boot application.
I. Exp: You can enable debug logs by
setting the logging level in
[Link]/[Link]:
II. Enabling debug from Command Line:
When running the application, you can
pass flags to enable debug:
[Link] Spring Boot Actuator :
If Actuator is included, you can change
log levels at runtime:
1. Add dependency:
<dependency>
<groupId>[Link]</groupId
>
<artifactId>spring-boot-starter-actuator</artif
actId>
</dependency>
2. Enable loggers endpoint in
[Link]:
[Link]=loggers
[Link] log level dynamically using HTTP
POST request:
Note: Explanation: This allows you to
increase log level at runtime
without restarting the application—
very useful in production
troubleshooting.
III. Programmatically Setting Log Level:
You can also set log level inside your application:
34. What is dependency Injection
and its types?
Dependency Injection (DI) is a design
pattern that enables us to produce
loosely coupled components. In DI, an
object's ability to complete a task
depends on another object. There three
types of dependency Injections.
Constructor injection: This is the most
common type of DI in Spring Boot. In
constructor injection, the dependency object
is injected into the dependent object's
constructor.
Setter injection: In setter injection, the
dependency object is injected into the
dependent object's setter method.
Field injection : In field injection, the
dependency object is injected into the
dependent object's field.
35. What is an IOC container?
An IoC (Inversion of Control) Container in Spring
Boot is essentially a central manager for the
application objects that controls the creation,
configuration, and management of dependency
injection of objects (often referred to as beans),
also referred to as a DI (Dependency Injection)
container.
36. What is the difference between
Constructor and Setter Injection?
Constructor Injection Setter Injection
Dependencies are Dependencies are
provided through the provided through
class constructor. setter methods.
Dependencies are Dependencies are set
given when the after the object is
object is created. created.
Makes the object Object is flexible
immutable (cannot (dependencies can be
change dependencies changed).
later).
Hard to override Easy to override
dependencies. dependencies.
1. What is Thymeleaf?
Thymeleaf is a Java-based server-
side template engine used in Java web
applications to render dynamic web pages. It is a
popular choice for server-side templating in the
Spring ecosystem, including Spring Boot.
2. Explain Spring Data and What is Data
JPA?
Spring Data
Spring Data is a part of the Spring
Framework that simplifies working with
databases.
It reduces boilerplate code by providing
ready-made repositories (interfaces) for data
access.
It supports different data stores like JPA,
MongoDB, Redis, Cassandra,
Elasticsearch, etc.
👉 In short: “Spring Data makes database
operations easier and consistent across different
databases.”
Spring Data JPA
Spring Data JPA is a module of Spring Data
that specifically works with relational
databases using JPA (Java Persistence
API).
It allows us to write repositories with almost
zero implementation code.
Example: Instead of writing SQL/JPQL
manually, we just declare methods in an
interface, and Spring generates the
implementation.
3. Explain Spring MVC
MVC stands for Model, View, and Controller.
Spring MVC is a web MVC framework built on
top of the Spring Framework. Spring MVC is a
web framework in the Spring ecosystem that
follows the MVC design pattern to build web
applications.
Model → Represents the data and business
logic.
View → Responsible for displaying the data
(UI, e.g., JSP, Thymeleaf).
Controller → Handles client requests,
processes them using services, and returns
the response/view.
4. What is Spring Bean?
An object that is managed by the Spring IoC
container is referred to as a spring bean. A
Spring bean can be any Java object.
4. What are Inner Beans in Spring?
Definition: Inner Beans are beans defined inside the <property>
or <constructor-arg> of another bean in the Spring
configuration file.
Usage: They are used when a bean is only required by a single
outer bean and is not shared anywhere else.
Scope: Inner Beans are always anonymous (no id/name) and
cannot be reused outside the outer bean.
<bean id="car" class="[Link]">
<property name="engine">
<bean class="[Link]"/> <!--
Inner Bean -->
</property>
</bean>
Here, the Engine bean is defined inside the Car
bean. It exists only for Car and cannot be
accessed elsewhere.
5. What is Bean Wiring?
Bean wiring is a mechanism in Spring that
is used to manage the dependencies
between beans. It allows Spring to inject
collaborating beans into each other. There
are two types of Bean Wiring:
Autowiring
Manual wiring
7. What Are Spring Boot DevTools Used
For?
Spring Boot DevTools is mainly used to
improve developer productivity during
development. It provides features like:
Automatic application restart
Fast application startup
Actuator endpoints
Additional development utilities
8. What error do you see if H2 is not
present in the class path?
[Link]:
[Link]
9. Mention the steps to connect the
Spring Boot application to a database
using JDBC.
To connect an external database like MySQL
or Oracle to a Spring Boot application using
JDBC, we need to follow below steps:
Add the dependency for the JDBC driver
of the database.
<!-- MySQL Database Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring JDBC -->
<dependency>
<groupId>[Link]</groupId
>
<artifactId>spring-boot-starter-jdbc</artifactId
>
</dependency>
Configure Database Properties in
[Link] or
[Link]:
[Link]=root
[Link]=Kanha@123
[Link]-class-
name=[Link]
[Link]=jdbc:mysql://localhost:3306/m
ydb
Create a JdbcTemplate bean.
Spring Boot automatically configures a
JdbcTemplate bean, which you can inject into
your Repository/Service classes.
Use the JdbcTemplate bean to execute
SQL queries and statements.
Test the Application
Run your Spring Boot application.
Call repository methods from a
Controller/Service to insert or fetch data .
10. Mention the advantages of the
YAML file over than Properties file and
the different ways to load the YAML file
in Spring boot.
Advantages of YAML over Properties
file:
Readable & Concise: YAML is easier to
read and write, especially for nested
configurations.
Supports Complex Data: YAML can handle
lists, maps, and hierarchical data better than
.properties files.
Structured Configuration: Makes it easier
to organize environment-specific settings.
Ways to Load YAML in Spring Boot:
[Link] [Link] (default) – Spring
Boot automatically reads it.
[Link] @ConfigurationProperties
annotation – Bind YAML properties to Java
classes.
3. Using YamlPropertiesFactoryBean –
Load YAML into Properties object manually if
needed.
11. What Do you understand about
Spring Data Rest?
Definition:
Spring Data REST is a module of Spring
Data that automatically exposes your
Spring Data repositories as RESTful
APIs without writing any controller code.
Purpose:
It simplifies building REST APIs for CRUD
operations on your entities, so
developers can focus on business logic
rather than boilerplate REST endpoints.
How it Works:
You define a JPA repository (like CrudRepository or
JpaRepository).
Spring Data REST automatically exposes REST endpoints
for your entities, supporting GET, POST, PUT, PATCH,
DELETE.
It also handles paging, sorting, and HATEOAS links
automatically.
12. Why is Spring Data REST not
recommended in real-world
applications?
Performance Issues- Performance may not
be optimal for very large-scale applications.
Versioning Problems- It can be difficult to
version the REST APIs exposed by Spring
Data REST.
Complex Relationships: - Handling entity
relationships and nested resources can
become tricky with Spring Data REST.
Filtering & Security Limitations-
Advanced filtering, validation, and security
configurations are harder to implement.
13. How is Hibernate chosen as the
default implementation for JPA without
any configuration?
Spring Boot automatically
configures Hibernate as the default JPA
implementation when we add the spring-
boot-starter-data-jpa dependency to our
project. This dependency includes the
Hibernate JAR file as well as the Spring Boot
auto-configuration for JPA.
14. Explain how to deploy to a different
server with Spring Boot?
Step 1: Build your Spring Boot
application.
Use Maven or Gradle to package your application.
mvn clean package
Step 2: Create a deployment
package(WAR - optional).
If your server requires a WAR, configure
Spring Boot to generate a WAR by extending
SpringBootServletInitializer.
Step 3: Deploy the deployment package
to the server.
Copy the JAR/WAR to the server.
For WAR: Drop it into the server’s webapps folder (Tomcat/WildFly).
For JAR: Run with java -jar [Link].
Step 4: Start the server.
WAR: Start the server normally (bin/[Link] for Tomcat).
JAR: Run the JAR on the server machine.
Step 5: Access the Application:
Open [Link] in the browser.
Rest API Interview Questions and
Answers
[Link] is REST?
REST (Representational State Transfer) is an
architectural style for designing networked
applications. It defines a set of principles for
how resources should be structured and
accessed over HTTP.
[Link] is REST API ?
OR)What is RESTful API?
OR) What are RESTful web services?
REST API (Representational State
Transfer Application Programming
Interface) is an implementation of REST
principles. It is an actual interface (software)
that allows clients to communicate with the
server using REST rules.
Uses Standard HTTP Methods: GET,
POST, PUT, DELETE to perform actions.
Stateless: Each request from the client
contains all information needed to process it.
Resource-Based: Interacts with resources
identified by URLs.
Uniform Interface: Provides a consistent
way to access and manipulate resources
across applications.
3. What difference between REST and
REST API?
REST REST API
REST (Representational State REST API is an implementation of
Transfer) is an architectural REST principles. It is an actual
style for designing networked interface (software) that allows
applications. It defines a set of clients to communicate with the
principles for how resources server using REST rules.
should be structured and
accessed over HTTP.
Conceptual/Design Practical/Implemented
principle service
Provides guidelines for Provides endpoints (URLs) for
building scalable, stateless clients to access and
services manipulate resources
Defines use of HTTP Uses HTTP methods to actually
methods (GET, POST, PUT, perform CRUD operations on
DELETE) for resource resources
operations
Use URLs to represent A web service like
resources and HTTP [Link]
methods to manipulate which allows GET, POST, PUT, DELETE on users
them
[Link] are the core principles of REST
architecture?
(Or)
What are the key principles of REST
architecture?
Statelessness : In REST, stateless
communication means that every client
request must contain all the information
necessary to understand and process that
request. The server does not maintain any
client context or session state between
requests
Client-Server Architecture: REST follows
a client-server model, where the client and
server are separate. The client is typically
responsible for presenting the user interface
and interacting with the user, while the
server handles the data and business logic.
Uniform Interface: REST requires that all
interactions between clients and servers
follow a uniform interface, which simplifies
the architecture. REST uses a consistent
way to access resources via HTTP
methods:
GET → Retrieve a resource
POST → Create a new resource
PUT → Update a resource
DELETE → Remove a resource
Resources are identified using URIs.( /users/123 identifies a user
resource.)
Cacheability: REST allows responses to be
explicitly called as cacheable or non-
cacheable. When a response is cacheable,
the client can store that response locally for
a specified period. This improves
performance and reduces server load.
Example: GET requests to fetch data can be
cached, but POST requests that modify data
should not be cached.
Layered System. A REST system can be
composed of multiple layers, where each
layer has a unique function.
Code on Demand (Optional): REST allows
servers to send executable code (like
JavaScript) to clients in response to a
request. Not commonly used, but part of
REST principles.
REST is stateless, client-server
based, uses a uniform interface with
HTTP methods, supports caching,
allows layered architecture, and
optionally supports code on demand.
These principles ensure scalability,
simplicity, and reliability of web
services.”
[Link] is the difference between REST
and SOAP?
REST SOAP (Simple Object
(Representation Access Protocol)
al State
Transfer )
REST is SOAP is a protocol-
an architectural based
style, not a
protocol
It uses standard It uses protocols (like
HTTP methods HTTP, SMTP, or FTP) for
(GET, POST, PUT, communication.
DELETE) for
communication.
REST can return SOAP uses XML
data in multiple exclusively as its
formats.(json/xml) message format
REST is stateless SOAP can be either
stateful or stateless,
REST is
Slower, heavier
generally faster an
due to XML format
d more efficient.
REST is simple and SOAP is more complex
flexible, with because it has a rigid
fewer rules and specification
standards to
follow
REST is widely SOAP is often used
used in web and in enterprise-level
mobile applications where
applications, advanced security,
especially for messaging reliability,
public-facing APIs and transactions are
(such as social needed.
media APIs, cloud
services, etc.).
4. What does HTTP stand for, and why
is it important in REST APIs?
“HTTP stands for Hypertext Transfer
Protocol, which is the foundation of
communication on the web. In REST APIs,
HTTP is important because REST uses HTTP
methods to perform operations on resources:
GET → Retrieve data
POST → Create a new resource
PUT → Update an existing resource
DELETE → Remove a resource
Each REST request includes an HTTP
method, headers, body, and sometimes
parameters. This defines the action, the
resource, and any extra info like
authentication.
REST is stateless, meaning every HTTP
request is independent and contains all the
information the server needs. This aligns
perfectly with how HTTP works.”
[Link] idempotency in REST APIs.
Idempotency in REST APIs means that no
matter how many times a client sends the
same request, the result on the server
remains the same and does not change after
the first execution.
GET, PUT, DELETE methods are typically
idempotent.
o GET → fetching data multiple times
doesn’t change it.
o PUT → updating a resource with the
same data multiple times results in the
same state.
o DELETE → deleting the same resource
multiple times has the same effect after
the first deletion.
POST is usually not idempotent because
sending the same request multiple times
may create multiple resources.
Example:
If you send a PUT request to update a
user’s email to abc@[Link],
sending it 5 times keeps the email the
same, so it’s idempotent.”
6. What is the difference between HTTP
GET, POST, PUT, and DELETE methods?
GET: The GET method retrieves data from
a specified resource. It is read-only and
does not modify the resource. For
example, GET /users would retrieve a list
of users. GET requests should be
idempotent, meaning multiple identical
requests should produce the same result
without side effects.
POST: The POST method sends data to the
server to create a new resource. For
example, POST /users might be used to
create a new user. Unlike GET, POST is not
idempotent, meaning multiple
identical POST requests might create
multiple resources.
PUT: The PUT method is used to update an
existing resource or create a new resource
if it does not exist. It requires the client to
send the full representation of the
resource. For example, PUT /users/1 would
update the user with ID 1. PUT is
idempotent, meaning if the client sends
the same PUT request multiple times, the
result will be the same.
DELETE: The DELETE method is used to
delete a resource. For
example, DELETE /users/1 would remove
the user with ID 1. DELETE requests are
generally idempotent because calling it
multiple times on the same resource
should have the same effect (i.e., the
resource is deleted once and does not
exist anymore).
6. What are HTTP status codes? Can
you give examples of 2xx, 4xx, and 5xx
codes?
HTTP status codes are three-digit numbers
returned by the server in response to an HTTP
request. They indicate the outcome of the request.
The codes are divided into categories based on
the first digit:
2xx (Successful Responses):
o 200 OK: The request was successful, and the
server has returned the requested data.
o 201 Created: The request was successful,
and a new resource was created as a result
(e.g., after a POST request).
o 204 No Content: The request was
successful, but there is no content to return
(e.g., after a DELETE request).
4xx (Client Errors):
o 400 Bad Request: The request was
malformed or invalid. The client should fix the
request before retrying.
o 401 Unauthorized: The client must provide
authentication credentials to access the
resource.
o 403 Forbidden: The server understood the
request but refuses to authorize it.
o 404 Not Found: The requested resource
could not be found on the server.
5xx (Server Errors):
o 500 Internal Server Error: A generic error
indicating that something went wrong on the
server.
o 502 Bad Gateway: The server received an
invalid response from an upstream server
while processing the request.
o 503 Service Unavailable: The server is
temporarily unable to handle the request,
often due to maintenance or overload.
7. What is the difference between PUT
and PATCH?
Feature PUT PATCH
Updates the entire Updates part of a
Purpose
resource resource
Full representation Only the fields to be
Payload
of the resource updated
Can create the
Typically does not create
Creation resource if it
the resource
doesn’t exist
Idempotent – Usually idempotent,
Idempoten same request but can vary
cy multiple times has depending on
same effect implementation
Update all user
Update only the email of
Example fields (name,
a user
email, etc.)
8. What is the role of a resource in a
REST API?
A resource is any object or concept
exposed by the API, like a user, product,
or image.
Every resource has a unique URI
(Uniform Resource Identifier) to identify
it.
Resources can have different
representations, like JSON or XML.
Clients interact with resources using HTTP
methods:
GET → retrieve data
POST → create a new resource
PUT/PATCH → update existing resource
DELETE → remove a resource
Resources are central to REST because
APIs are designed to manipulate
resources and represent their current
state.
9. What is an endpoint in a REST API?
An endpoint in a REST API is a specific
URL where a client can interact with a
particular resource or group of
resources.
It represents a location on the server
where operations (CRUD) can be
performed using HTTP methods.
Each endpoint corresponds to a distinct
functionality or action that can be
performed on a resource.
Examples:
GET /users → fetch all users
GET /users/{id} → fetch a user by ID
POST /users → create a new user
PUT /users/{id} → update a user
DELETE /users/{id} → delete a user
Base URL + endpoint path forms the full URL for accessing a resource:
[Link]
o Base URL: [Link]
o Endpoint: /users/{id}
10. What does "stateless" mean in the
context of REST?
In REST, stateless communication means
that every client request must contain all
the information necessary to understand
and process that request.
The server does not maintain(store) any
client context or session or state between
requests
Statelessness ensures REST APIs are
scalable, simple, and performant
because each request is independent
and self-contained
13. What is JSON, and why is it used in
REST APIs?
JSON (JavaScript Object Notation) is a
lightweight, human-readable data format
that is commonly used to represent
structured data.
It is primarily used to exchange data
between a client and a server in REST
APIs
JSON represents data as key-value pairs
and can be easily mapped to objects in
most programming languages.
JSON is used for several reasons:
Simplicity: JSON is simple to read and write. Its syntax is
straightforward and uses basic structures like arrays and objects.
Lightweight: JSON messages are generally more compact than
XML, which reduces the overhead of sending data over the
network.
Compatibility: JSON is natively supported by most web browsers
and languages (including JavaScript), making it easy to work with in
web applications and APIs.
Language Agnostic: JSON is not tied to any specific programming
language, which means it can be parsed and generated in virtually
any language, such as JavaScript, Python, Java, Ruby, etc.
14. What is XML, and why is it used in
REST APIs?
XML (eXtensible Markup Language):
Definition: XML is a markup language
designed to store and transport data in a
structured, hierarchical format using tags.
Unlike HTML, it focuses on data
representation, not presentation.
Why XML is used in REST APIs:
[Link] Data: Allows complex data
to be represented with nested
elements.
[Link]-independent: Can be read
and processed by any programming
language.
[Link] Format: Widely
supported in enterprise systems and
legacy applications.
[Link] Validation: Supports schema
definitions (XSD) to validate data
structure.
[Link] to JSON: While JSON is
more common in modern REST APIs,
XML is still used when strict document
structure or enterprise standards are
needed.
Exp;
15. What is the difference between
JSON and XML?
Feature JSON XML
JSON uses a simpler,
XML uses a more
lightweight syntax
verbose, tag-based
consisting of key-value
structure with
pairs enclosed in curly
Syntax opening and closing
braces ({}) for objects and
tags (e.g., <user>,
square brackets ([]) for
</user>).
arrays.
Harder to read
Readability Easy to read and write due to tags and
nesting
Data and
document-
Data
Data-centric, mainly centric,
Representati
objects/arrays supports
on
attributes &
metadata
Parsing Fast and easy, Slower, requires
Feature JSON XML
natively supported in complex parsers
JavaScript or libraries
more verbose and
more compact, making it typically requires
Size more efficient in terms of more bandwidth to
data transmission. transmit the same
data.
Supported,
Namespaces Not supported avoids naming
conflicts
16. What is the HTTP request-response
cycle in RESTful web services?
Client Request:
The client (browser, mobile app, or API
client) sends an HTTP request to the
server, including:
HTTP Method (GET, POST, PUT, DELETE)
URI of the resource
Headers (optional metadata like Content-
Type, Authorization)
Body (optional data for POST/PUT)
Server Processing:
The server receives the request and
performs actions such as:
Fetching or updating data from the
database
Executing business logic
Authenticating the client
Server Response:
The server sends an HTTP response
containing:
Status code (e.g., 200 OK, 404 Not
Found, 500 Internal Server Error)
Headers (metadata about the response)
Body (optional data in JSON, XML, or
other formats)
Client Handling:
The client processes the response by:
Displaying data to the user
Handling errors based on status codes
17. What is URL encoding, and why is it
important in REST APIs?
URL encoding (also called percent-encoding)
is the process of converting characters in a
URL into a format that can be safely
transmitted over the internet.
This is necessary because URLs can only
safely contain a limited set of characters.
Characters such as spaces, punctuation, and
non-ASCII characters are not allowed in a
URL in their original form, so they must be
encoded.
URL encoding is important in REST APIs for
the following reasons:
Preventing errors
Ensuring proper interpretation
Ensuring security
18. What are query parameters in REST
APIs? Provide an example.
Query parameters are key-value pairs added
to the end of a URL to pass additional
information to the server in a REST API
request.
They are commonly used for filtering,
sorting, or pagination of resources.
Query parameters follow the ? character in a
URL and are separated by an &. Each
parameter consists of a key and a value.
Syntax: [Link]
key1=value1&key2=value2
Exp:
Filter users by age and city : GET /users?age=25&city=Delhi → Fetches all users
who are 25 years old and live in Delhi.
Pagination : GET /products?page=2&limit=10 → Fetches page 2 of products,
showing 10 items per page.
Search: GET /books?title=java → Returns books with the word "java" in their title.
[Link] is the role of the HTTP header in
REST API requests?
HTTP headers are key-value pairs sent in
both requests and responses that carry
metadata about the request/response.
They do not change the resource itself
but provide extra information to the
server or client.
Why they are important in REST APIs?
Authentication & Security
o Headers can carry credentials or tokens for authorization.
o Example:
o Authorization: Bearer <token>
Content-Type
o Specify the format of request/response (JSON, XML, etc.).
o Examples:
o Content-Type: application/json
o Accept: application/xml
Accept: The Accept header specifies what kind of response format
the client expects (e.g., application/json or application/xml).
Caching
o Control how responses should be cached.
o Example:
o Cache-Control: no-cache
Custom Metadata
o Developers can create custom headers (e.g., X-Request-ID) for
tracking and debugging.
Language/Localization
o Indicate user language preferences.
o Example:
o Accept-Language: en-US
Example REST API Request with Headers:
GET /users/123 HTTP/1.1
Host: [Link]
Authorization: Bearer abc123
Content-Type: application/json
Accept: application/json
[Link] are request and response bodies
in REST APIs?
Request Body
The request body is the part of an HTTP
request where the client sends data to the
server.
Used when the client wants to create,
update, or send details about a resource.
Usually used with methods like POST, PUT,
or PATCH.
✅ Example (POST – creating a new user):
POST /users HTTP/1.1
Host: [Link]
Content-Type: application/json
{
"name": "Kanhu",
"email": "kanhu@[Link]",
"password": "12345"
}
Request body contains the new user’s details
in JSON format.
Response Body
The response body is the part of the HTTP
response where the server sends data
back to the client.
Used to return requested resources,
confirmation messages, or error details.
Commonly formatted as JSON or XML.
✅ Example (Response for above POST request):
HTTP/1.1 201 Created
Content-Type: application/json
{
"id": 101,
"name": "Kanhu",
"email": "kanhu@[Link]",
"message": "User created successfully"
}
Here:
Response body contains the created user’s
info plus a confirmation message.
Key Difference
Response
Aspect Request Body
Body
Who
Server →
sends Client → Server
Client
it?
Provide
Provide data for the result of
Purpos server to process processing
e (create/update/sear (data,
ch) confirmatio
n, error)
Returning
Exampl Sending user details created
e when creating an user details
Usage account or an error
message
[Link] do you handle errors in REST
APIs?
Error handling in REST APIs is done by
combining HTTP status codes, structured
error messages, consistent response format,
and proper logging. This ensures that clients
can handle errors programmatically and
developers can troubleshoot effectively.
HTTP Status Codes: The most common
way to indicate errors in REST is
through HTTP status codes. These codes
provide a standardized way of
communicating the success or failure of a
request.
o 4xx: Client-side errors (e.g., 400
Bad Request, 404 Not Found).
o 5xx: Server-side errors (e.g., 500
Internal Server Error).
Error Message in Response Body: In addition to
HTTP status codes, many APIs return a detailed
error message in the response body, describing the
problem in more detail. This message may include:
o A brief error code or message (e.g., User not found).
o A description or details to help the client understand
what went wrong.
o Any corrective actions the client can take (e.g., "check if
the ID is correct").
Consistency
Use a uniform error format across all
endpoints.
Example: Always return {error, message,
status, timestamp}.
Logging & Monitoring (Server-Side)
Log errors with details for debugging.
Use monitoring tools (like ELK, Datadog,
Prometheus) to track API failures.
[Link] is a 404 Not Found status code?
The 404 Not Found status code is part of
the 4xx class of HTTP status codes, which
represent client errors. A 404 status code
specifically indicates that the requested
resource could not be found on the server.
This can occur for several reasons:
The URI (Uniform Resource
Identifier) specified by the client is incorrect
or does not exist.
The resource (such as a user, product, or
file) has been deleted or moved.
The resource might never have existed on
the server in the first place.
[Link] is a 500 Internal Server Error
status code?
The 500 Internal Server Error status code
is part of the 5xx class of HTTP status
codes, which indicate server-side errors.
A 500 error is a generic error message that
signifies the server encountered an
unexpected condition that prevented it
from fulfilling the request.
This error does not provide specific details
about the issue, as it typically indicates a
failure on the server’s end, such as:
Unhandled exceptions in the application
code.
Database connection failures or timeouts.
Server misconfigurations or failures in
other critical components.
Resource exhaustion (e.g., memory, CPU).
A 500 status code indicates that the
problem is not caused by the client’s
request, but instead by an internal issue
on the server.
[Link] is CORS, and how does it relate
to REST APIs?
CORS stands for Cross-Origin Resource
Sharing. It’s a browser security feature
that controls whether a web application
running on one domain can make requests
to a server hosted on another domain.
By default, web browsers block cross-
origin requests for security reasons, to
prevent cross-site request forgery
(CSRF) and cross-site scripting
(XSS) attacks. So if my frontend is on
[Link] and my REST API is on
[Link] the browser will
block it unless the API explicitly allows it
using CORS headers.
[Link] is OAuth and how is it used in
REST APIs?
OAuth (Open Authorization) is an
authorization protocol used to grant
third-party applications limited access to
a user’s resources without sharing their
credentials (such as username and
password).
OAuth is widely used in REST APIs for
securing and delegating authorization.
OAuth issues access tokens that are used in REST
API requests.”
Mention why we need OAuth
(problem it solves):
👉 “Normally, if an app wanted to access
my Gmail data, I’d have to share my
Gmail username and password, which is
insecure. With OAuth, I only give
permission, and Google gives the app a
temporary access token. My credentials
are never shared.”
Explain the main components (keep it
simple):
Resource Owner – The user (who owns the data).
Client – The app that needs access (e.g., Spotify).
Authorization Server – Issues tokens (e.g., Google/Facebook Auth server).
Resource Server – The API where resources are stored (e.g., Gmail API).
Walk through the OAuth Flow
(storytelling helps)
👉 “Let’s say Spotify wants to access my Gmail contacts so I can invite friends.”
Spotify (Client) redirects me to Google’s Authorization Server.
I (Resource Owner) log in with my Google account and approve access.
Google sends Spotify an Authorization Code.
Spotify exchanges that code for an Access Token from Google.
Spotify now calls Google’s REST APIs with:
Authorization: Bearer <access_token>
The Resource Server (Google API) validates the token and returns my
contacts.
👉 “In this way, Spotify can access my data securely without knowing my Gmail password.”
Mention OAuth Flows briefly (good
impression)
Authorization Code Flow → Secure, used by web apps.
Implicit Flow → Used by SPAs (less secure).
Client Credentials Flow → Used when no user is involved (system-to-
system).
[Link] are API keys, and how are they
used for authentication?
An API key is a unique identifier used to
authenticate a client to an API.
It is a simple string (often a long
alphanumeric key) that is passed with the
API request to verify the identity of the client
and ensure that the client is authorized to
access the requested resources.
API keys are typically used in public APIs or
in situations where the authentication
requirements are simpler. When the client
sends a request to the server, the API key is
included in the request headers, URL, or
body.
Common ways API keys are used:
In the URL
Example: [Link]
apikey=12345
In the headers:
Example: Authorization: ApiKey 12345
👉 “So whenever the client sends a request,
the server checks the key. If it’s valid, the
server processes the request.”
👉 “For example, when we use Google Maps
API in a project, Google provides an API key.
Without this key, our requests to Google
Maps would be rejected.”
They are less secure than OAuth because
they don't offer advanced features
like expiration or scoping of permissions.
Advantages:
Easy to implement.
Good for public APIs or simple services.
Can be used to track usage (rate limiting, analytics).
Limitations:
Not very secure (can be exposed in URLs, logs).
Cannot define granular permissions (unlike OAuth).
Usually does not expire automatically
[Link] is rate limiting in the context of
REST APIs?
Restricts the number of requests a client
can make in a given time.
Prevents abuse, overloading, and denial-
of-service attacks.
Example: 100 requests per minute per
user.
[Link] does pagination work in REST
APIs?
Pagination is a technique used in REST
APIs to manage large sets of data by
dividing them into smaller, more
manageable chunks (pages).
This helps reduce the size of individual API
responses and improves performance,
especially when clients only need a portion
of the data at a time.
Pagination is typically implemented
using query parameters to specify the
page number and the number of items per
page.
Common pagination parameters:
page: The page number of the results (e.g.,
page=2).
limit (or per_page): The number of items per
page (e.g., limit=10).
Example of a paginated API request:
In the response, the API may include additional
metadata such as:
The total number of items (total_count).
The number of items on the current page
(count).
Links to the next/previous pages (next,
previous).
Example response with pagination:
Pagination is critical in APIs that deal with
large datasets to prevent excessive
memory use and improve response times.
[Link] is HATEOAS in RESTful services?
HATEOAS stands for: Hypermedia As The
Engine Of Application State.
It is a constraint of REST that says:
“A client interacts with a REST API entirely
through the hypermedia provided
dynamically by server responses.”
In simple words:
The server tells the client what actions it
can perform next by including links in the
response.
The client doesn’t need to hardcode URL
paths—it discovers them dynamically from
the server.
Example: Suppose we have a REST API for
a user resource:
GET /users/1 → Response:
tells the client:
_links
o How to update this user
o How to delete this user
o How to fetch all users
The client doesn’t need to construct URLs manually—it just follows
these links.
[Link] is a REST API versioning
strategy?
REST API versioning is used to manage
changes and updates in an API without
breaking existing clients.
It ensures backward compatibility while
allowing new features or changes.
[Link] can you ensure security in REST
APIs?
To secure REST APIs, we authenticate users
using API keys, OAuth, or JWT, authorize
access based on roles, encrypt data with
HTTPS, validate inputs, apply rate limiting,
configure CORS, and monitor logs for
suspicious activity. These practices ensure
that APIs are safe, reliable, and maintain data
integrity.
[Link] is JWT (JSON Web Token) and
how is it used in REST APIs?
JWT (JSON Web Token) is an open standard
(RFC 7519) used to securely transmit
information between parties as a JSON object.
It is commonly used
for authentication and authorization in REST
APIs, providing a compact and self-contained
way to represent claims between two parties.
A JWT typically consists of three parts:
[Link]: Contains metadata about the
token, including the signing algorithm (e.g.,
HS256).
[Link]: Contains the claims or the data
you want to transmit. This might include user
information, roles, or custom data. Note that
this data is not encrypted by default, just
base64 encoded.
[Link]: The signature is created by
taking the encoded header and payload,
applying the specified algorithm (e.g., HMAC
SHA256), and signing it with a secret key.
The signature ensures that the token hasn’t
been tampered with.
JWT is used in REST APIs in the following way:
[Link] user logs in, and the server generates a
JWT containing the user's identity and other
claims (e.g., roles).
[Link] server sends the JWT to the client, which
stores it (usually in localStorage or a cookie).
[Link] client includes the JWT in
the Authorization header of subsequent API
requests.
[Link] server decodes the JWT and validates it.
If valid, the server processes the request.
Example JWT in the Authorization header:
Authorization: Bearer <JWT_Token>
JWT is stateless (i.e., no session data is stored
on the server), which makes it well-suited for
REST APIs, where scalability and statelessness
are important design considerations.
[Link] can you handle user
authentication in REST APIs?
User authentication in REST APIs is typically
done using methods like Basic
Authentication, OAuth, JWT (JSON Web
Token), or Session Cookies. The two most
common and modern approaches are:
Token-based Authentication (e.g., JWT):
When a user logs in, the server validates
their credentials (usually via a POST
request with the user's username and
password).
If the credentials are valid, the server
generates a JWT (JSON Web Token) and
sends it back to the client.
The client stores the token (typically in
localStorage or a cookie) and includes
the token in the Authorization header of
future API requests.
Example of a request with a JWT token:
GET /profile
Authorization: Bearer <JWT_Token>
OAuth 2.0 Authentication:
OAuth allows users to grant third-party
applications limited access to their
resources without sharing credentials.
It typically involves three
components: Resource Owner, Client,
and Authorization Server.
OAuth provides flows like Authorization
Code Flow and Implicit Flow, allowing
more granular access control.
Additionally, API keys and Basic
Authentication (username/password in the
Authorization header) are also used, though
they are less secure and flexible compared
to token-based approaches.
[Link] is the purpose of a REST API
documentation?
1. Explains API functionality:
o Shows what the API does, what resources
are available, and which operations
(GET, POST, PUT, DELETE) can be
performed.
2. Describes endpoints clearly:
o Each endpoint’s URL, supported HTTP
methods, request parameters, and
response structure are documented.
3. Provides request and response
examples:
o Helps developers understand how to
interact with the API effectively.
4. Clarifies authentication and
authorization:
o Explains how to provide credentials (API
keys, OAuth tokens, JWT, etc.) for
accessing the API.
5. Reduces errors and
misunderstandings:
o Developers can follow the
documentation instead of guessing how
to use the API.
6. Supports collaboration:
o Makes it easier for front-end, back-end,
and third-party developers to integrate
with the API.
[Link] tools can you use to test REST
APIs?
Postman:
o A widely used tool for testing and
debugging APIs. It allows you to create
and send HTTP requests, inspect
responses, and automate testing with
scripts.
o Features: Organize requests in
collections, run tests using scripts,
generate code snippets, and handle
authentication.
Insomnia:
o A REST client similar to Postman but
focused on simplicity and ease of use. It
provides features for sending requests,
viewing responses, and debugging API
calls.
cURL:
o A command-line tool used to transfer
data to/from a server using various
protocols, including HTTP. It's particularly
useful for quick tests or scripting.
Swagger (OpenAPI):
o An open-source framework for API
documentation that allows for interactive
API exploration. You can define the API
using the OpenAPI Specification and test
it directly from the documentation.
SoapUI:
o A comprehensive testing tool for both
REST and SOAP APIs. It allows you to
create tests, run them, and analyze the
results.
JMeter:
o Primarily a load testing tool, JMeter is
often used to test the performance and
scalability of APIs under heavy loads.
Paw (for macOS):
o A REST client that allows you to interact
with and test APIs. It's similar to
Postman, but with a focus on macOS
users.
[Link] is Postman, and how is it used
to test REST APIs?
What is Postman?
Postman is a popular API testing tool used by
developers to test, debug, and document REST
APIs. It provides an easy-to-use interface to
send HTTP requests and view responses
without writing code.
How Postman is used to test REST APIs
[Link] Requests:
o Enter the API endpoint URL and select
the HTTP method (GET, POST, PUT,
DELETE).
[Link] Headers and Body:
o Include request headers (like Content-
Type or Authorization) and request body
(for POST/PUT requests).
[Link] Request and View Response:
o Execute the request and view the
response status, headers, and body
(JSON, XML, etc.) in Postman.
[Link] & Collections:
o Save requests in collections for testing
multiple endpoints and automating
workflows.
[Link] Variables:
o Use variables for different environments
(development, staging, production) for
flexibility.
[Link] is a client-server architecture in
REST?
In REST, the client-server architecture
separates the user interface from the backend
logic. The client sends requests, and the server
processes them and returns data. This
separation ensures scalability, statelessness,
and clear division of responsibilities.
[Link] do you implement caching in
REST APIs?
Caching is used to store responses
temporarily so that repeated requests for
the same resource can be served faster,
reducing server load and improving
performance.
We can use HTTP headers like Cache-
Control and ETag, server-side caches
like Redis, client-side caching in
browsers, or even CDNs caching.
It improves performance and reduces load
on the server
[Link] is a web service in the context
of REST?
A web service is a way for different
applications (clients and servers) to
communicate over the web using standard
protocols like HTTP.
When we talk about RESTful web services, it
specifically means:
The service follows REST principles
(stateless, resource-based, uses standard
HTTP methods).
It exposes resources (like users, products,
orders) that clients can interact with.
Clients interact with these resources through
HTTP requests (GET, POST, PUT, DELETE).
Responses are usually in JSON or XML
format, making it easy for applications to
understand.
Key Points:
1. Stateless: Each request contains all
information needed to process it.
2. Resource-based: Every object or
entity has a URI.
3. Standard Methods: Uses HTTP
methods to perform CRUD operations.
4. Interoperable: Any client that can
make HTTP requests can use the
service.
[Link] is the purpose of the HTTP
"Accept" header in REST APIs?
The Accept header tells the server what format(s) of
response the client can handle.
It helps the server decide whether to return data in JSON,
XML, or another media type.
Exp:
GET /users/1
Accept: application/json
Server sees Accept: application/json →
returns the response in JSON format.
If the client used Accept: application/xml
→ server returns XML.
1. What is the difference between a
resource and a representation in REST?
In REST, a resource is an entity or object
that is represented by a URL (Uniform
Resource Locator).
It is the thing that the API exposes for
interaction. Resources can be anything,
such as users, products, or articles.
A representation is the actual data of a
resource that is transferred between the
client and the server. It can be in various
formats, such as JSON, XML, or HTML.
For example:
A resource could be a user with the URL
/users/12345.
The representation of that resource might be
a JSON object:
Rest API Interview Questions for
Intermediates
1. How can you handle rate limiting in
a REST API?
Rate limiting is a technique used to control
the number of requests a client can make to
a REST API within a given time window. It
helps prevent abuse, server overload, and
ensures fair usage among clients.
How it works:
The server defines a limit (e.g., 100 requests
per minute per client).
Each client request is tracked (usually by IP
address or API key).
If a client exceeds the limit, the server
responds with a 429 Too Many Requests
status code.
Some APIs provide headers like:
X-RateLimit-Limit → Max requests allowed
X-RateLimit-Remaining → Requests left
X-RateLimit-Reset → Time until limit resets
Implementation Approaches:
Token Bucket: Clients have tokens; each
request consumes a token. Tokens refill over
time.
Leaky Bucket: Requests flow through a
fixed-size bucket at a steady rate.
Fixed Window / Sliding Window: Count
requests in fixed or sliding time intervals.
Example:
A client can make 100 requests per hour.
If the client sends the 101st request, the server responds
with:
HTTP/1.1 429 Too Many Requests
Retry-After: 3600
2. What is the difference between
authentication and authorization in
REST APIs?
Feature Authentication Authorization
Determines what the
Definition Verifies who the user/client is.
user/client can do.
Access control and
Purpose Identity verification.
permissions.
When it Happens before Happens after
occurs accessing the resource. authentication.
Uses roles,
Uses credentials like permissions, or
How it
username/password, API access policies to
works
key, or JWT token. allow or deny
actions.
Logging in with a Checking if the user
Example username and can edit or delete a
password. resource.
3. What are the common methods to
secure REST APIs?
Authentication & Authorization:
o Implement token-based authentication (e.g., JWT or OAuth
2.0) to ensure that only authenticated users or applications can
access the API.
o Use role-based access control (RBAC) or attribute-based
access control (ABAC) to restrict access based on user roles
and permissions.
HTTPS (SSL/TLS):
o Always use HTTPS to encrypt communication between clients
and servers, preventing eavesdropping, man-in-the-middle
attacks, and data tampering.
API Keys:
o Use API keys for identifying clients and services accessing your
API. Ensure that API keys are sent over HTTPS and are kept
secret.
Input Validation:
o Perform strict input validation to prevent common security
vulnerabilities such as SQL injection and Cross-Site
Scripting (XSS).
CORS (Cross-Origin Resource Sharing):
o Configure CORS to control which domains are allowed to access
your API. This can prevent unauthorized cross-site requests from
malicious websites.
Rate Limiting:
o Implement rate limiting to prevent abuse, Denial-of-Service
(DoS) attacks, and overuse of the API by limiting the number of
requests a client can make within a given time frame.
Logging & Monitoring:
o Implement logging and monitoring to track requests, detect
suspicious activity, and audit access to sensitive data.
HMAC (Hash-based Message Authentication Code):
o Use HMAC to ensure message integrity and authenticity. This
involves signing requests with a secret key to verify that the
message has not been altered.
4. How do you implement pagination in
a REST API?
Pagination can be implemented using methods like:
Offset-Based
Pagination: Uses offset and limit query
parameters to fetch specific slices of data (e.g., ?
offset=10&limit=10).
Cursor-Based Pagination: Uses a cursor
(pointer to a specific record) to fetch data
incrementally (e.g., ?cursor=abc123).
Page-Based Pagination: Uses page numbers
and page size to fetch data (e.g., ?
page=2&pageSize=10).
5. What is the difference between
stateless and stateful services?
Stateless and stateful are terms that describe how
a service handles data persistence and session
management:
[Link]:
In a stateless service, each request is treated
independently. The server does not store any
information about the client between
requests. Each request must contain all the
information needed for processing, such as
authentication credentials, request
parameters, etc.
o Advantage: Stateless services are scalable
because the server doesn't need to maintain
session information.
o Example: A RESTful API is typically stateless, where
the server does not retain any session information
between requests.
[Link]:
In a stateful service, the server maintains
the state of the client across multiple
requests. The server stores session
information, which can be used to track
user interactions, preferences, and other
context.
o Advantage: Stateful services can provide
more personalized experiences since the
server knows the client's history and can
remember past actions.
o Example: A web application that uses cookies to
maintain user sessions (like when you log in and the
server remembers your authentication state).
6. How do you perform input validation
in REST APIs?
Input validation is essential for ensuring the
integrity, security, and correctness of data
sent to a REST API. It prevents malicious or
malformed data from being processed by the
server.
Steps to perform input validation:
Validate Query Parameters:
o Check that query parameters are of the
correct type (e.g., strings, integers) and
within valid ranges.
o Example: Ensure that a page parameter
is an integer and not negative.
Validate Request Body:
o If the request contains a body (e.g., for
POST or PUT), validate the structure
(e.g., check required fields, data types,
and length constraints).
o Use JSON Schema or libraries
like Joi ([Link]) to enforce schema rules.
Sanitize Input:
o Sanitize input to prevent security
vulnerabilities like SQL
injection and XSS by removing special
characters or encoding inputs as
necessary.
Use Regular Expressions:
o Regular expressions can be used to
validate certain patterns, such as email
formats, phone numbers, or URLs.
Error Handling:
o Provide clear error messages when
validation fails. For example:
o {
o "error": "Invalid input",
o "message": "The 'email' field must be a valid email
address."
o }
Whitelist Validation:
o Validate the inputs against a whitelist of
allowed values, ensuring only known,
trusted data is processed.
7. How would you handle versioning in
a REST API?
API versioning ensures backward
compatibility and allows changes or
enhancements to be made to an API without
breaking existing clients.
Common approaches to versioning a REST
API:
URI Path Versioning:
o Include the version in the API path.
Example:
/api/v1/users
/api/v2/users
Query Parameter Versioning:
o Specify the version via a query
parameter.
/api/users?version=1
Header Versioning:
o Include the version in the HTTP request
header, often using the Accept header.
Accept: application/[Link].v1+json
Content Negotiation:
o Use content negotiation headers (like
Accept and Content-Type) to serve
different versions of the API based on the
client’s request
8. What are the best practices for
designing RESTful endpoints?
Use Nouns for Resource Names:
o Resources should be nouns representing entities (e.g., users,
products), not verbs.
o Example: /users for a collection, /users/{id} for a specific user.
Use HTTP Methods Correctly:
o Use GET for retrieving data, POST for creating
resources, PUT/PATCH for updating, and DELETE for removing
resources.
Use Plural Nouns for Collections:
o Represent collections with plural nouns. For example, /users for a
collection of users, /products for a collection of products.
Provide Clear Resource Hierarchy:
o Use nested resources when representing relationships.
o Example: /users/{userId}/orders for retrieving orders of a specific
user.
Return Proper HTTP Status Codes:
o Return status codes that reflect the outcome of the request (e.g.,
200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500
Internal Server Error).
Use Consistent Naming Conventions:
o Follow a consistent naming convention for endpoints, parameters,
and data (e.g., camelCase or snake_case).
Limit the Number of Endpoints:
o Keep the API surface small and manageable by focusing on core
functionality and minimizing unnecessary endpoints.
9. What is content negotiation in REST
APIs?
Content negotiation allows clients and servers to agree on the format
of the response data based on the client’s preferences and the server’s
capabilities. It is typically handled using HTTP headers like Accept,
Content-Type, and Accept-Encoding.
Key components of content negotiation:
Accept header: Used by the client to specify the desired response
format. Example:
Accept: application/json
Content-Type header: Indicates the format of the request body.
Example:
Content-Type: application/json
10. How do you handle errors and
exceptions in REST APIs?
11. What is the difference between
HTTP methods like GET, POST, PUT,
PATCH, and DELETE?
12. How do you handle authorization in
a REST API?
13. What is an API Gateway, and what
role does it play in microservices?
14. How do you manage database
transactions in REST APIs?
15. How do you log requests and
responses in a REST API?
16. What are some common API design
patterns?
17. How do you authenticate using
OAuth 2.0 in a REST API?
18. What are the differences between
Basic Authentication and OAuth?
19. How would you handle multi-
language or internationalization (i18n)
in REST APIs?
20. How do you handle session
management in stateless REST APIs?
21. What are the advantages of using
JWT tokens for authentication?
22. What is the role of the
"Authorization" header in HTTP
requests?
23. How do you implement custom
headers in RESTful APIs?
24. What are the disadvantages of
using URL-based parameters for
sensitive information?
25. What is OpenAPI (Swagger), and
how is it useful in documenting REST
APIs?
26. What are the different types of
HTTP caching mechanisms for REST
APIs?
27. How do you handle cross-origin
resource sharing (CORS) in REST APIs?
28. How do you handle asynchronous
processing in REST APIs?
29. How would you implement logging
and monitoring for a REST API?
30. What is the concept of
"Idempotency" in RESTful APIs?
31. How do you handle file uploads and
downloads in REST APIs?
32. What is the difference between
synchronous and asynchronous API
calls?
33. How do you design REST API routes
to be idempotent?
34. What is the difference between a
REST API and GraphQL?
35. What is a 415 Unsupported Media
Type error in REST APIs?
36. How would you manage timeouts
and retries in a REST API?
37. What are the benefits and
challenges of implementing
microservices with REST APIs?
38. How do you handle long-running
operations in REST APIs?
39. How can you implement a retry
mechanism for failed API requests?
40. How can you prevent abuse and
DDoS attacks on a REST API?
Rest API Interview Questions for
Experienced
1. How do you optimize the
performance of a REST API?
2. What are the key differences
between REST and gRPC?
3. How do you scale a REST API for a
high-traffic application?
4. How would you design a fault-
tolerant and resilient REST API system?
5. How do you implement API
monitoring and logging at scale?
6. What is the purpose of an API
gateway in a microservices
architecture?
7. How would you handle complex
transactions in REST APIs, especially
with distributed systems?
8. What are some strategies for load
balancing REST API requests?
9. How do you implement distributed
caching for REST APIs?
10. How would you handle
authentication and authorization in a
microservices architecture using REST
APIs?
11. What are some of the challenges of
working with RESTful APIs in a
microservices environment?
12. How do you implement rate limiting
at scale in a REST API?
13. What is the significance of API
design patterns like CRUD, Repository,
and Service Layer in REST APIs?
14. How do you implement API
versioning without breaking existing
consumers?
15. How do you perform data validation
and sanitization at scale in a REST API?
16. How do you implement service
discovery in REST API-based systems?
17. What is a "circuit breaker" pattern,
and how does it work with REST APIs?
18. How do you manage a large number
of API endpoints and maintain
consistency?
19. How do you deal with the N+1 query
problem in REST APIs?
20. What is the role of webhooks in
REST APIs, and how would you
implement them?
21. How do you ensure the consistency
of data in distributed REST API
systems?
22. What are the differences between
REST and WebSockets, and when would
you use each?
23. How would you implement GraphQL
over REST for complex API
requirements?
24. How do you manage and handle
schema migrations in a RESTful API
backend?
25. How do you protect sensitive data
in a REST API?
26. What is an API management
platform, and how does it benefit large-
scale REST API deployments?
27. How do you deal with API consumer
versioning, especially with a large
number of clients?
28. How do you ensure high availability
for REST APIs in a cloud environment?
29. How would you design a secure API
authentication mechanism for third-
party clients?
30. What are some advanced error
handling techniques for large-scale
REST APIs?
31. What is the importance of API
observability, and how do you achieve
it?
32. How do you handle eventual
consistency in a REST API?
33. How would you implement a
message queue in REST API to handle
background tasks?
34. How would you handle scaling a
REST API horizontally?
35. How do you monitor the
performance of a REST API in
production?
36. What are the trade-offs between
REST and Event-Driven Architectures?
37. How do you ensure API backward
compatibility when making changes to
an API?
38. What is an API rate-limiting
strategy, and how do you implement it
for millions of requests per minute?
39. How would you implement a REST
API with a real-time communication
feature (e.g., WebSocket)?
40. How do you ensure efficient data
retrieval and reduce latency in a REST
API?
Basics of REST
1. What is REST?
2. What are the key principles of REST
architecture?
3. Difference between REST and SOAP.
4. Explain idempotency in REST APIs.
5. Difference between PUT and POST
methods.
6. When would you use PATCH
method?
2. HTTP & Status Codes
7. What are the common HTTP status
codes and their meaning?
8. Difference between 200, 201, 204,
400, 404, 500 status codes.
9. Difference between client-side and
server-side errors.
10. How do you handle errors in a REST
API?
3. Spring Boot & REST
11. How do you create a REST API in
Spring Boot?
12. Explain @RestController vs
@Controller.
13. What is @RequestMapping and its
variants (@GetMapping, @PostMapping,
etc.)?
14. How to pass parameters in REST API
(path variable, request param, request
body)?
15. What is ResponseEntity in Spring
Boot?
4. Request & Response Handling
16. Difference between @RequestParam
and @PathVariable.
17. How to handle JSON
request/response in Spring Boot?
18. How do you implement validation in
REST API (@Valid, @Validated)?
19. Difference between @RequestBody
and @ModelAttribute.
20. How to return custom HTTP
responses?
5. Exception Handling
21. How do you handle exceptions in
Spring Boot REST API?
22. Difference between
@ControllerAdvice and
@ExceptionHandler.
23. How to create custom exception
responses?
6. Security
24. How to secure REST APIs in Spring
Boot?
25. Difference between authentication
and authorization.
26. Explain JWT and how to implement it
in REST APIs.
27. Difference between Basic Auth,
OAuth2, and JWT.
7. Advanced Concepts
28. Explain HATEOAS.
29. Difference between synchronous
and asynchronous REST APIs.
30. Explain API versioning in REST.
31. How to handle pagination and
sorting in REST API?
32. Difference between stateless and
stateful services.
8. Testing & Documentation
33. How to test REST APIs in Spring
Boot?
34. Explain Postman, Swagger, and
OpenAPI.
35. How to document REST APIs using
Swagger?
9. Performance & Best Practices
36. What is caching in REST APIs and
how to implement it?
37. How to handle large file uploads in
REST APIs?
38. How to handle concurrency and rate
limiting in REST APIs?
39. Difference between blocking and
non-blocking APIs (Spring WebFlux).
40. Best practices for designing REST
APIs.
CORE JAVA INTERVIEWS QUESTION
Beginner Level Questions
[Link] is Java?
Java is a high-level, object-oriented programming
language developed by Sun Microsystems. It is
designed to be platform-independent and follows
the "Write Once, Run Anywhere" (WORA) principle(
once a program is written, it can run on any
platform without modification)
2. Is Java Platform Independent if then how?
3. What is JVM?
4. What is JIT?
5. What is a classloader?
[Link] are the main features of Java?
Or) What are the top Java Features?
Key features of Java include:
Object-oriented
Platform-independent (via the Java Virtual
Machine)
Simple and easy to learn
Distributed computing support (via RMI and EJB)
Multi-threading
Robust and secure (garbage collection, exception
handling, etc.)
Dynamic and extensible
Architecture Neutral : it is not dependent on the
architecture
High Performance
[Link] the difference between JDK, JRE, and
JVM.
JDK: JDK stands for Java Development Kit. It is a
set of development tools and libraries used to
create Java programs. It works together with the
JVM and JRE to run and build Java applications..
JRE: JRE stands for Java Runtime
Environment, and it provides an environment to
run Java programs on the system. The
environment includes Standard Libraries and JVM.
JVM: JVM stands for Java Virtual Machine. It's
responsible for executing the Java program.
8. Explain different data types in Java.
9. When a byte datatype is used?
10. What is the difference between [Link],
[Link], and [Link]?
11. Difference in the use of print, println, and
printf.
12. What are operators?
13. 40. How many types of operators are
available in Java?
14. 41. Explain the difference between >> and
>>> operators.
15. What is the significance of the main
method in Java?
In Java, the main method is the entry point for any
standalone Java application. When you run a Java
program, the JVM looks for this method to start
execution.
The signature of the main method is:
public: The method is public so that it can be
accessed by the JVM from anywhere.
static: The static keyword allows the JVM to call the
method without creating an instance of the class.
void: This means the method does not return any
value.
String[] args: This parameter allows command-
line arguments to be passed to the program. It is an
array of String values.
The main method is necessary because it tells the JVM
where to begin the execution of a Java program.
Without the main method, the JVM would have no
starting point to launch the program.
16. What is the difference between a class
and an object in Java?
Feature Class Object
A class is a blueprint or
An object is an instance of a
Definition template for creating
class.
objects.
Purpose Defines properties Represents a real-world entity
(fields) and behaviors using those properties and
(methods). behaviors.
Feature Class Object
Does not occupy
Memory Occupies memory when
memory until an object
Usage created.
is created.
Defined using the class Created using the new
Creation
keyword. keyword.
class Car {
String color;
Example Car myCar = new Car();
void accelerate ( ){ ….. }
}
Logical / conceptual Physical / real instance of the
Nature
entity. class.
Variables (fields) and Actual data (values of fields)
Contains
methods. and can invoke methods.
Like a blueprint of a car Like a real car built from that
Analogy
model. blueprint.
Used to create multiple Each object has its own state
Scope
objects. (data values).
Exists as long as the
Exists as long as the
Lifetime reference to it remains
program is loaded.
accessible.
17. What is an instance variable?
An instance variable is a variable declared
inside a class but outside any method,
constructor, or block. Each object created from
the class has its own copy of instance variables,
and these variables represent the state of the
object.
Instance variables are non-static and belong to
individual objects.
They are initialized to default values if not
explicitly initialized (e.g., null for objects, 0 for
integers).
18. What is a constructor in Java?
A constructor in Java is a special method used to
initialize objects when they are created. It has the
same name as the class and does not have a
return type. Constructors are called automatically
when an object of a class is instantiated.
Default constructor: If no constructor is
explicitly defined, Java provides a default
constructor that initializes object fields to default
values.
Parameterized constructor: A constructor that
accepts arguments to initialize an object with
specific values.
19. What happens if you don't provide a
constructor in a class?
20. What do you understand by copy
constructor in Java?
21. Where and how can you use a private
constructor?
22. What are the differences between the
constructors and methods?
23.
24.
25. What is the difference between == and
equals() in Java?
== operator is used for comparing primitive
data types values or checking if two
references point to the same object.
.equals() is a method used for comparing the
content or values of objects. It's usually
overridden in custom classes for meaningful
comparison.
26. What is an array in Java, and how is it
declared?
An array in Java is an object that holds a
fixed-size collection of elements of the same
type. Arrays are used when you need to store
multiple values in a single variable.
Declaration and initialization:
Arrays have a fixed size, which means that once
the size is specified, it cannot be changed. You
can access individual elements using an index,
where the first element is at index 0.
Example :
27. What are the types of an array?
28. What is the difference between int array[]
and int[] array?
29. How to copy an array in Java?
30. What do you understand by the jagged
array?
31. Is it possible to make an array volatile?
32. What are the advantages and
disadvantages of an array?
33. What is an object-oriented paradigm?
34. What are the main concepts of OOPs in
Java?
35. What is the difference between an object-
oriented programming language and an object-
based programming language?
36. . How is the ‘new’ operator different from
the ‘newInstance()’ operator in Java?
37. What is the difference between static
(class) method and instance method?
38. What are the different ways to create
objects in Java?
39. What are the advantages and
disadvantages of object cloning?
40.
41. Explain the concept of encapsulation in Java.
Encapsulation is one of the four fundamental
OOP principles.
The Process of binding(wrapping)
properties(variables) and behaviour(methods)
into a single unit or a class is called
Encapsulation.
This is done by making the instance
variables private and providing public methods
(getters and setters) to access or modify them.
Benefits of Encapsulation:
o Data hiding: it is a way of restricting the
access of our data members by hiding the
implementation details. Encapsulation also
provides a way for data hiding. The user will
have no idea about the inner implementation
of the class.
o Control over data: You can add logic in the
getter and setter methods to control how data
is accessed or modified.
o Reusability: Encapsulation also improves the
re-usability and is easy to change with new
requirements
o Maintainability: Encapsulation helps in
maintaining and modifying code since
changes in the internal workings of a class do
not affect other parts of the program.
In this example, the name variable is
encapsulated, and access to it is controlled
through the getName() and setName()
methods.
42. What are the access modifiers in Java?
In Java,access modifiers are keywords used to
define the visibility or scope of classes, methods,
and variables. There are four primary access
modifiers in Java:
public:
o When a class, method, or variable is declared
public, it is accessible from any other class or
package in the application.
o Example: A public method can be called from
anywhere.
private:
o When a method or variable is declared
private, it is only accessible within the same
class where it is defined. It is not accessible
from outside the class or package, ensuring
data encapsulation.
o Example: A private variable or method cannot
be accessed directly by other classes.
protected:
o The protected modifier makes the method or
variable accessible within the same package
and by subclasses (even if they are in
different packages).
o Example: A protected variable can be
accessed by subclasses but not by other
classes in the same package unless they are
subclasses.
Default (Package-Private):
o When no access modifier is specified, the
method or variable has package-
private access, meaning it is accessible only
within classes in the same package.
o Example: A class or variable with no modifier
is visible only to classes in the same package.
43. What is method overloading?
The process of creating multiple methods with
same name but with different formal arguments
is called Method Overloading
Method Overloading depends only upon method
signature but not on access specifier,access
modifier and return type.
The Main purpose of Method Overloading is to
perform the same operation in different ways
44. What is method overriding?
Method overriding occurs when a subclass
provides a specific implementation for a method
that is already defined in its superclass.
The process of overriding super class non-static
method with sub-class non-static methods and
this overriding takes place only if we create the
object of sub-class
To perform this method overriding we have to
follows some rules and they are-
Inheritance is mandatory
The super class non-static method and sub-
class non-static method declaration should be
same but implementation should be different
The access specifier of sub-class non-static
method should be greater than or equals to
super class non-static method.
Object should be created for sub-class
45. What is the difference between final, finally,
and finalize() in Java?
final:
o Used to define constants, prevent method
overriding, and prevent inheritance.
o Can be applied to variables, methods, and
classes:
1. final variable: The value cannot be
changed once initialized.
2. final method: The method cannot be
overridden by subclasses.
3. final class: The class cannot be
subclassed.
Example:final int x = 10; // Cannot change the
value of x
finally:
o A block of code that follows a try-catch block
and will always execute, regardless of
whether an exception is thrown or not. It's
commonly used for cleanup operations (like
closing files or releasing resources).
o Syntax:
finalize():
o A method in the Object class that is called by
the garbage collector just before an object is
destroyed. It gives objects a chance to clean
up resources before they are garbage
collected. However, its use is discouraged in
modern Java programming in favor of using
try-with-resources and explicit resource
management.
46. What is the difference between ArrayList and
LinkedList in Java?
47. How does a for-each loop work in Java?
The for-each loop (also called the enhanced for
loop) in Java provides a simpler way to iterate
over arrays and collections without needing an
index variable. It is used to iterate over elements
of a collection (such as arrays, lists, or sets).
The syntax for a for-each loop:
Type: The type of elements in the collection (e.g.,
int, String).
element: The variable that will hold the current
element in each iteration.
collection: The array or collection you are
iterating over.
Exp;
48. What is the default value of an
uninitialized variable in Java?
In Java, uninitialized instance
variables (variables defined inside a class but
outside any method or constructor) are
automatically assigned default values by the Java
compiler, depending on their data type. Local
variables, however, must be explicitly initialized
before use.
The default values are:
Numeric types (byte, short, int, long, float,
double): 0 or 0.0
Boolean: false
Character: \u0000 (null character)
Object references (String, Arrays, etc.): null
49. What is a static variable? How is it different
from an instance variable?
A static variable is a variable that belongs to the
class rather than to instances (objects) of the
class. It is shared by all instances of the class, and
its value is common across all objects.
Static variable:
o Declared with the static keyword.
o It has the same value across all instances of
the class.
o It's initialized only once when the class is
loaded.
Instance variable:
o Belongs to each individual object (instance) of
the class.
o Each object has its own copy of instance
variables.
Example;
50. What is a static method? Can you call a static
method without creating an object?
A static method is a method that belongs to the
class rather than to instances of the class. You can
call a static method without creating an object of
the class. Static methods can access only static
variables and other static methods within the
class.
Key points:
o Static methods are called using the class
name, not through an object.
o They cannot access instance variables or
instance methods directly.
Exp;
51. What is the difference between String,
StringBuilder, and StringBuffer in Java?
1. String:
o Immutable: Once a String object is created, its
value cannot be changed.
o Any operation that modifies a String results in
the creation of a new String object.
o Less efficient for frequent modifications (like
concatenation) due to the overhead of
creating new objects.
2. StringBuilder:
o Mutable: StringBuilder objects can be
modified after creation without creating new
objects.
o It is more efficient than String for string
manipulation (like concatenation).
oThread-unsafe (not synchronized), which
means it is faster in single-threaded
environments.
3. StringBuffer:
o Mutable: Similar to StringBuilder, but it
is thread-safe.
o It is synchronized, which makes it slower than
StringBuilder in single-threaded scenarios but
suitable for multi-threaded environments.
Example of StringBuilder vs StringBuffer:
StringBuilder sb = new
StringBuilder("Hello");
[Link](" World");
StringBuffer sbf = new
StringBuffer("Hello");
[Link](" World");
52. What is a package in Java?
A package in Java is a namespace that organizes
a set of related classes and interfaces. It helps to
avoid naming conflicts and to manage large
codebases by grouping similar classes. Java
packages can also help with access control and
provide a structured way of organizing files within
a project.
Types of packages:
1. Built-in packages: These are predefined
packages provided by the Java API. For example,
[Link] (for utility classes like ArrayList,
HashMap), [Link] (for input/output operations),
etc.
2. User-defined packages: These are packages
created by the developer to organize their own
classes.
To use classes from a package:
53. What is the use of the super keyword in Java?
The super keyword in Java is used to refer to
the superclass (parent class) of the current
object. It is typically used in two main ways:
1. Accessing superclass methods:
If a method is overridden in the subclass, you
o
can use [Link]() to call the superclass
version of the method.
2. Accessing superclass constructors:
o The super() keyword can be used to invoke a
constructor of the superclass. It must be the
first statement in the subclass constructor.
Exp;
Calling a superclass constructor:
54. What is the difference between public,
private, protected, and default access modifiers?
In Java, access modifiers determine the visibility
and accessibility of classes, methods, and
variables. The four access modifiers are:
1. public:
o The member is accessible from
anywhere in the program, both inside and
outside the class, and from any package.
[Link]:
o The member is accessible only within the
same class. It cannot be accessed from other
classes, even if they are in the same package.
[Link]:
o The member is accessible within the same
class, same package, and subclasses (even
if the subclass is in a different package).
[Link] (Package-Private):
o When no access modifier is specified, the
member has package-private access. It is
only accessible within classes that belong to
the same package.
55. What is an interface in Java?
An interface in Java is a reference type, similar to
a class, but it is a collection of abstract methods
(methods without a body). It cannot contain
instance variables or constructors, and all
methods in an interface are
implicitly public and abstract (until Java 8, which
introduced default methods). Interfaces are used
to specify a set of methods that a class must
implement.
Key points about interfaces:
Interfaces define abstract behavior that classes
can implement.
A class can implement multiple interfaces,
allowing Java to support multiple inheritance of
behavior.
56. Give some features of the Interface.
57. What is a marker interface?
58.
59. What is an abstract class in Java, and how is it
different from an interface?
An abstract class in Java is a class that cannot
be instantiated on its own and may contain
both abstract methods (methods without a
body) and concrete methods (methods with an
implementation). An abstract class is used to
represent a common base class for other classes
that share common behavior.
Differences between abstract class and
interface:
1. Abstract class:
o Can have
both abstract and concrete methods.
o Can have instance variables.
oCan have constructors.
o A class can inherit only one abstract
class (single inheritance).
2. Interface:
o Can only have abstract methods (before
Java 8).
o Cannot have instance variables (only
constants).
o Cannot have constructors.
o A class can implement multiple
interfaces (supports multiple inheritance).
Example of abstract class:
60. What is polymorphism in Java?
Polymorphism in Java is the ability of an object
to take on many forms. Specifically, it allows one
interface to be used for a general class of actions.
The specific action is determined at runtime.
There are two types of polymorphism in Java:
1. Compile-time polymorphism (Method
Overloading):
o Occurs when multiple methods have the same
name but different parameters.
Exp;
1. Runtime polymorphism (Method Overriding):
o Occurs when a subclass provides a specific
implementation of a method that is already
defined in its superclass. The method to be
called is determined at runtime based on the
object type.
Exp;
61. What is runtime polymorphism or dynamic
method dispatch?
62. Can we override the static method?
63. Can we override the overloaded method?
64. Can we overload the main() method?
65. Can we override the private methods?
66. Can we change the scope of the overridden
method in the subclass?
67. Can you have virtual functions in Java?
68.
69. What do you mean by aggregation?
70. What is the ‘IS-A ‘ relationship in OOPs
Java?
71. What is inheritance in Java?
Inheritance is one of the four pillars of object-
oriented programming (OOP) in Java. It allows a
new class (child or subclass) to inherit the
properties and methods of an existing class
(parent or superclass). The subclass can then add
additional features or modify the inherited
behavior.
Key benefits of inheritance:
Reusability: The subclass reuses the code from the
parent class.
Extensibility: The subclass can extend the
functionality of the parent class
In this example, Dog inherits the eat() method
from the Animal class.
72. What are the different types of inheritance
in Java?
73. What is multiple inheritance? Is it
supported by Java?
74. Is there any limitation to using Inheritance?
75. Although inheritance is a popular OOPs
concept, it is less advantageous than
composition. Explain.
76. What is an association?
77. What do you mean by aggregation?
78. What is the composition of Java?
79. 100. Can the constructor be inherited?
80. What is the difference between this and super
in Java?
1. this:
o Refers to the current object (the object
whose method or constructor is being
invoked).
o It can be used to call instance variables,
methods, and constructors within the current
class.
Exp;
[Link]:
o Refers to the parent class of the current
object.
o It is used to access superclass methods and
constructors .
Exp;
81. What is the difference between throw and
throws in Java?
1. throw:
o Used to explicitly throw an exception from a
method or a block of code.
o You can throw both checked and unchecked
exceptions.
o
2. throws:
o Used in a method declaration to declare
that a method may throw one or more
exceptions.
o It is used to indicate that the method does not
handle the exception itself, and it will be
handled by the calling method.
82. What is exception handling in Java?
Exception handling in Java is a mechanism to
handle runtime errors (exceptions) so that the
normal flow of the program can be maintained.
Java provides a robust mechanism to catch and
handle exceptions using the try, catch, finally, and
throw keywords.
Main components:
1. try block: Contains the code that might throw an
exception.
2. catch block: Catches the exception and handles
it.
3. finally block: Executes code after the try and
catch blocks, regardless of whether an exception
is thrown or not.
4. throw keyword: Used to throw an exception
manually.
5. throws keyword: Declares the exceptions a
method might throw.
83. What is the try-catch block in Java?
The try-catch block in Java is used to handle
exceptions in a controlled way. The try block
contains code that may potentially throw an
exception, and the catch block contains code that
handles the exception if one is thrown.
Structure:
try block: The code that might throw an
exception is placed here.
catch block: This block catches and handles the
exception, allowing the program to continue
execution without crashing.
finally block (optional): This block will always
execute, regardless of whether an exception
occurred or not, making it suitable for resource
cleanup (like closing files or database
connections).
Syntax:
Exp;
84. What is the difference between checked and
unchecked exceptions?
1. Checked exceptions:
o These are exceptions that are checked at
compile time. The programmer is forced to
handle these exceptions explicitly (using try-
catch or by declaring them with throws).
o Examples include IOException, SQLException,
ClassNotFoundException.
o Compiler enforces handling: If the code
throws a checked exception but does not
handle it, the compiler will generate an error.
[Link] exceptions:
o These are exceptions that occur at runtime
and are not checked at compile-time. These
include subclasses of RuntimeException and
Error.
o Examples include NullPointerException,
ArrayIndexOutOfBoundsException,
ArithmeticException.
o Not mandatory to handle: The compiler
does not require you to handle unchecked
exceptions, but they should still be handled in
some cases to ensure program stability.
85. What are some common types of exceptions
in Java?
ArithmeticException: Thrown when an
exceptional arithmetic condition has occurred
(e.g., division by zero).
int result = 10 / 0; // Throws ArithmeticException
NullPointerException: Thrown when trying to
access an object or invoke a method on a null
object.
String s = null;
[Link](); // Throws NullPointerException
ArrayIndexOutOfBoundsException: Thrown
when accessing an array with an invalid index.
int[] arr = new int[5];
arr[10] = 10; // Throws
ArrayIndexOutOfBoundsException
IOException: Thrown when there are issues with
input/output operations (e.g., file not found).
FileInputStream fis = new
FileInputStream("[Link]"); // Throws IOException
ClassNotFoundException: Thrown when trying
to load a class via its name but the class is not
found
[Link]("[Link]"); //
Throws ClassNotFoundException
SQLException: Thrown when a database error
occurs.
Connection conn =
[Link]("jdbc:mysql://localh
ost:3306/db");
IllegalArgumentException: Thrown when an
illegal or inappropriate argument is passed to a
method.
int number = [Link]("abc"); // Throws
IllegalArgumentException
86. Difference between an Error and an
Exception.
87. . Explain the hierarchy of Java Exception
classes.
88. Explain Runtime Exceptions.
89. Is it necessary that each try block must be
followed by a catch block?
90. What is exception propagation?
91. What will happen if you put [Link](0)
on the try or catch block? Will finally block
execute?
92. What is a NullPointerException?
A NullPointerException (NPE) occurs when your
code attempts to use a reference that points to
null (an uninitialized object). This exception is a
runtime exception, and it indicates that your code
is trying to access methods or fields of an object
that doesn't exist (i.e., is null).
Common causes:
Dereferencing null when trying to call a method on
a null object.
Accessing an element in an array that is null.
Modifying or accessing a null collection.
93. What is a ClassNotFoundException?
A ClassNotFoundException is a checked
exception that occurs when Java tries to load a
class by name using methods like [Link]()
or [Link](), but it cannot find the
class.
Common causes:
The class file is not in the classpath.
The class file is missing or misplaced.
The class was not properly compiled or packaged.
Exp;
try {
[Link]("[Link]"); // Throws
ClassNotFoundException if class is not found
} catch (ClassNotFoundException e) {
[Link]("Class not found.");
94. What is the difference between String and
StringBuilder in Java?
[Link]:
o Immutable: Once a String object is created,
its value cannot be changed. Any operation
that modifies a string results in the creation of
a new String object.
o Less efficient for concatenation or frequent
modifications because each modification
creates a new object.
[Link]:
o Mutable: StringBuilder objects can be
modified without creating new objects.
o More efficient than String for concatenating
strings in loops or when frequent
modifications are required.
Exp;
String str = "Hello";
str = str + " World"; // A new String object is
created
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // The StringBuilder is modified
without creating a new object
95. What is multitasking?
96. What do you mean by a Multithreaded
program?
97. What are the advantages of
multithreading?
98. Differentiate between process and thread?
99. Describe the life cycle of the thread?
100. Explain suspend() method under the
Thread class.
101. Explain the main thread under Thread class
execution.
102. What is a daemon thread?
103. What are the ways in which a thread can
enter the waiting state?
104. What is a Java thread? How do you create a
thread?
Or) What are the advantages of
multithreading?
A Java thread is a lightweight process that allows
concurrent execution of tasks in a program. It is
part of the Java concurrency model and allows a
program to execute multiple tasks in parallel,
improving performance in multi-core processors.
There are two ways to create a thread in Java:
1. By extending the Thread class:
o You can create a new thread by subclassing
the Thread class and overriding its run()
method.
[Link] implementing the Runnable interface:
o You can also create a thread by implementing
the Runnable interface and passing it to a
Thread object.
105. What is the purpose of the wait() and notify()
methods in Java?
The wait() and notify() methods are part of
the Object class and are used for inter-thread
communication in Java, typically when using
multiple threads that need to communicate or
synchronize their actions.
1. wait():
o Causes the current thread to release the
lock it holds and enter the waiting state. The
thread will stay in the waiting state until
another thread sends a signal (via notify() or
notifyAll()).
o Must be called inside a synchronized block or
method.
2. notify():
o Wakes up one thread that is waiting on the
object's monitor (lock). If multiple threads are
waiting, one of them is chosen randomly to
resume.
o Must also be called inside a synchronized
block or method.
Example:
106. What is the purpose of the synchronized
keyword in Java?
The synchronized keyword in Java is used to
control access to a block of code or an object by
multiple threads. It ensures that only one thread
at a time can access the synchronized code or
resource, preventing race conditions and
ensuring thread safety.
Method-level synchronization: If a method is
declared as synchronized, the thread holds the
object’s monitor (lock) while executing that
method, preventing other threads from executing
synchronized methods on the same object.
Block-level synchronization: You can also
synchronize specific blocks of code within a
method, providing more fine-grained control over
thread synchronization.
Exp;
107. What is a deadlock in Java?
A deadlock in Java occurs when two or more
threads are blocked forever, waiting for each other
to release locks on resources. This can happen
when each thread holds a lock on one resource
and is waiting for a lock on another resource that
the other thread is holding.
Deadlock condition:
1. Mutual exclusion: At least one resource is held in a
non-shareable mode (i.e., only one thread can use
the resource at a time).
2. Hold and wait: A thread holding at least one
resource is waiting to acquire additional resources
that are currently being held by other threads.
3. No preemption: Resources cannot be forcibly
taken from threads holding them; they must be
released voluntarily.
4. Circular wait: A circular chain of threads exists,
where each thread is waiting for a resource held
by the next thread in the chain.
Example of deadlock:
In this example, two threads are in a circular wait,
causing a deadlock situation.
108. What are the different types of Thread
Priorities in Java? And what is the default
priority of a thread assigned by JVM?
109. Why Garbage Collection is necessary in
Java?
110. What is the drawback of Garbage
Collection?
111. Explain the difference between a minor,
major, and full garbage collection.
112. . Name some classes present in
[Link] package.
113. What is Collection Framework in Java?
114. Explain various interfaces used in the
Collection framework.
115. What is a Vector in Java?
116. What is a priority queue in Java?
117. Explain the LinkedList class.
118. What is the Stack class in Java and what
are the various methods provided by it?
119. What is Set in the Java Collections
framework and list down its various
implementations?
120. What is the HashSet class in Java and how
does it store elements?
121. What is LinkedHashSet in Java Collections
Framework?
122. What is a Map interface in Java?
123. Explain Treemap in Java
124. What is EnumSet?
125. What is BlockingQueue?
126. What is the ConcurrentHashMap in Java and
do you implement it?
127. Can you use any class as a Map key?
128. What is an Iterator?
129. Differentiate between Iterable and Iterator.
130. What is an enumeration?
131. What is the difference between Collection
and Collections?
132. Differentiate between Array and ArrayList
in Java.
133. What is the difference between Array and
Collection in Java?
134. Difference between ArrayList and
LinkedList
135. Differentiate between the Singly Linked
List and Doubly Linked List.
136. Differentiate between Queue and Stack.
137. Differentiate between ArrayList and Vector
in Java.
138. What is the difference between Iterator and
ListIterator?
139. Differentiate between HashMap and
HashTable.
140. Differentiate between HashMap and
TreeMap.
141. What is the difference between Iterator and
Enumeration?
142. What is the difference between Comparable
and Comparator?
143. What is the difference between Set and
Map?
144. Differentiate between Queue and Deque.
145. Differentiate between PriorityQueue and
TreeSet.
146. Differentiate between HashSet and
TreeSet.
147. What is JDBC?
148. What is JDBC Driver?
149. What are the steps to connect to the
database in Java?
150. What are the JDBC API components?
151. What is JDBC Connection interface?
152. What does the JDBC ResultSet interface?
153. What is the JDBC Rowset?
154. What is the role of the JDBC DriverManager
class?
155.
Intermediate Level Questions
1. What are the differences between ArrayList and
Vector?
2. What is the Collections framework in Java? Name
some commonly used classes.
3. What is the HashMap class in Java? How is it
different from TreeMap?
4. What is the difference between HashMap and
Hashtable?
5. How does garbage collection work in Java?
6. What are weak references in Java?
7. What is the role of the clone() method in Java?
8. What is the difference between shallow copy and
deep copy?
9. What is a Singleton class? How can you create one
in Java?
10. What is the transient keyword in Java?
11. What is the purpose of the volatile keyword in
Java?
12. What are the advantages of using the final
keyword with classes, methods, and variables?
13. What are Lambda expressions in Java?
Provide an example.
14. What are Functional interfaces in Java?
15. What is the difference between Runnable and
Callable in Java?
16. What is the difference between ArrayList and
LinkedList in terms of performance?
17. What is the difference between ==
and .equals() in terms of object comparison?
18. How does HashSet work in Java? What are its
benefits?
19. What is the Iterator interface in Java, and how
is it used?
20. What is the Comparable interface in Java?
21. What is the Comparator interface, and how is
it different from Comparable?
22. What is the difference between String and
StringBuffer in terms of immutability?
23. What are the different types of threads in
Java?
24. What is a thread pool in Java, and how does it
work?
25. What is the ExecutorService in Java?
26. How does synchronization work in Java?
27. What is the difference between wait() and
sleep() methods in Java?
28. What is the join() method in Java threads?
29. What is the difference between final, finally,
and finalize in Java?
30. What is a Stack and Queue in Java? Explain
their differences.
31. What is the difference between HashMap and
LinkedHashMap in Java?
32. What is a soft reference in Java?
33. What is the difference between ArrayList and
Vector in terms of performance?
34. What are generics in Java, and why are they
used?
35. How do you implement a thread-safe
collection in Java?
36. What is the try-with-resources statement in
Java?
37. What is the significance of the enum type in
Java?
38. What is the difference between a List, Set,
and Map in Java?
39. What are the different types of exceptions in
Java? Explain them with examples.
40. What is reflection in Java?
Experienced Level Questions
1. Explain the Java memory model (JMM) and how
synchronization affects it.
2. What are the design patterns you have used in
Java, and explain one in detail?
3. How does Java’s garbage collection work? Explain
the generational garbage collection approach.
4. What is the difference between synchronized block
and synchronized method in Java?
5. Explain how the volatile keyword ensures thread
safety in Java.
6. How do you prevent deadlock in Java?
7. What are the differences between ExecutorService
and ForkJoinPool?
8. What are Functional Programming concepts in
Java 8? Explain some of the key features.
9. How do you implement custom serializable classes
in Java?
10. Explain the Java Reflection API and how you
use it.
11. What is the [Link] package, and how does it
improve I/O operations over [Link]?
12. How does Java’s Stream API` work? Provide
examples of its usage.
13. What is a lazy initialization in Java, and how
do you implement it?
14. How do you handle memory leaks in Java
applications?
15. What are the different ways to handle
concurrency in Java?
16. What is a cyclic barrier in Java, and where
would you use it?
17. Explain the difference between ThreadLocal
and synchronized keyword in Java.
18. How do you implement thread-safe singleton
class in Java?
19. What are immutable objects in Java? Explain
how to create them.
20. What is Java NIO (New I/O), and what are its
advantages over classic I/O?
21. What are annotations in Java? How do you
create custom annotations?
22. How do you implement producer-consumer
problem in Java?
23. What is the observer design pattern, and how
is it implemented in Java?
24. What are Java’s concurrent collections?
Provide examples.
25. What is the purpose of Java’s Future and
Callable interfaces?
26. How does Java 8 handle default methods in
interfaces?
27. Explain the Fork/Join Framework in Java and
when to use it.
28. How would you optimize performance in a
multithreaded Java application?
29. How does the Java ClassLoader work?
30. What is the difference between final, finally,
and finalize in detail?
31. What is the Proxy Design Pattern in Java, and
how is it implemented?
32. How does Spring Framework use Java
reflection?
33. Explain how the Composite Design Pattern
works in Java.
34. What is a hash code in Java, and how is it
used in collections?
35. How does Java’s HashMap` handle collisions?
36. What is dependency injection in Java, and how
is it used in frameworks like Spring?
37. What is the difference between deep cloning
and shallow cloning in Java?
38. What are the best practices to handle large-
scale enterprise Java applications?
39. How do you improve the memory footprint of
a Java application?
40. Explain the concept of Reactive Programming
in Java.
CORE JAVA CODING QUESTION
Common Questions:
1. Write a program to check if a number is even or
odd.
2. Write a program to find the largest of three
numbers.
3. Write a program to swap two numbers without
using a third variable.
4. Write a program to check if a year is a leap year
or not.
5. Write a program to print the multiplication
table of a number.
6. Write a program to reverse a number.
7. Write a program to count digits in a number.
8. Write a program to check if a character is a
vowel or consonant.
9. Write a program to print all prime numbers
between 1 and 100.
10. Write a program to check if a number is
prime or not.
2. Arrays
Concepts tested: array traversal, searching,
sorting, two-pointer logic
🔹 Coding Questions:
1. Find the largest and smallest element in an
array.
2. Find the second largest element in an array.
3. Reverse an array without using another array.
4. Check if two arrays are equal or not.
5. Find the sum and average of elements in an
array.
6. Remove duplicates from a sorted array.
7. Find the missing number in an array from 1 to
N.
8. Rotate an array by K positions.
9. Find all pairs in an array whose sum equals a
given number.
10. Merge two sorted arrays.
11. Move all zeros to the end of the array.
12. Find the frequency of each element in an
array.
13. Sort an array using bubble sort / selection
sort / insertion sort.
14. Implement binary search on a sorted array.
15. Find the intersection and union of two
arrays.
🧵 3. Strings
Concepts tested: String, StringBuilder,
StringBuffer, immutability, manipulation
🔹 Frequently Asked:
1. Reverse a string without using built-in reverse()
method.
2. Check if a string is a palindrome.
3. Count vowels and consonants in a string.
4. Find the frequency of characters in a string.
5. Remove all duplicate characters from a string.
6. Find the first non-repeating character in a
string.
7. Check if two strings are anagrams.
8. Count the number of words in a string.
9. Find the occurrence of a substring in a string.
10. Convert the first letter of each word to
uppercase.
11. Replace all spaces in a string with “-”.
12. Find the longest word in a sentence.
13. Reverse each word in a string individually.
14. Check if two strings are rotations of each
other.
15. Remove all special characters from a string.
🔢 4. Numbers and Math Logic
Concepts tested: logic building, loops,
conditionals
🔹 Common Questions:
1. Find factorial of a number using recursion and
iteration.
2. Check if a number is Armstrong.
3. Check if a number is a palindrome.
4. Print Fibonacci series up to N.
5. Find the Nth Fibonacci number using recursion.
6. Find GCD and LCM of two numbers.
7. Find sum of digits of a number.
8. Check if a number is a perfect number.
9. Convert decimal to binary and vice versa.
10. Find all prime factors of a number.
11. Find the power of a number using
recursion.
12. Print all strong numbers between 1 to
1000.
🧱 5. Object-Oriented Programming (OOP)
Concepts tested: classes, objects, constructors,
inheritance, polymorphism, abstraction,
encapsulation
🔹 Practical Coding Scenarios:
1. Create a class Employee with id, name, and
salary. Write methods to display details.
2. Demonstrate constructor overloading.
3. Demonstrate method overloading and
overriding.
4. Implement inheritance with base class Shape
and derived classes Circle, Rectangle.
5. Create an interface Animal and implement it in
multiple classes.
6. Create an abstract class Bank with abstract
method getRateOfInterest().
7. Demonstrate encapsulation using private fields
and public getters/setters.
8. Write a program showing super and this
keyword usage.
9. Demonstrate runtime polymorphism using
method overriding.
10. Demonstrate static and non-static blocks
execution order.
🧰 6. Collections Framework
Concepts tested: ArrayList, LinkedList, HashMap,
HashSet, Iterator, Stream API
🔹 Interview Favorites:
1. Add and retrieve elements from an ArrayList.
2. Remove duplicates from an ArrayList.
3. Sort elements in an ArrayList.
4. Find the frequency of words using HashMap.
5. Iterate a HashMap using entrySet.
6. Check if two HashMaps are equal.
7. Find duplicate elements in a List.
8. Convert an ArrayList to an array and vice versa.
9. Sort a map by keys and by values.
10. Merge two HashMaps.
11. Find the first non-repeated element in a list
using LinkedHashMap.
12. Difference between HashSet,
LinkedHashSet, and TreeSet (with examples).
13. Convert a list to set and set to list.
14. Iterate over a collection using iterator and
for-each loop.
15. Filter a list using Stream API.
🧠 7. Exception Handling
Concepts tested: try-catch-finally, throw, throws,
custom exceptions
🔹 Programs:
1. Write a program to handle divide-by-zero
exception.
2. Create a custom exception InvalidAgeException.
3. Demonstrate multiple catch blocks.
4. Use finally block to release resources.
5. Write a program with throw and throws
keyword difference.
6. Nested try-catch example.
7. Handle NullPointerException and
ArrayIndexOutOfBoundsException.
💾 8. File Handling
Concepts tested: FileReader, FileWriter,
BufferedReader, BufferedWriter, Serialization
🔹 Programs:
1. Read and write content to a file.
2. Copy content from one file to another.
3. Count number of words, lines, and characters in
a file.
4. Check if a file exists or not.
5. Append text to an existing file.
6. Serialize and deserialize an object.
7. Delete a file from directory.
🔁 9. Multithreading
Concepts tested: Thread class, Runnable
interface, synchronization, sleep, join
🔹 Questions:
1. Create and start a thread using Thread class.
2. Create a thread using Runnable interface.
3. Demonstrate synchronized keyword.
4. Use sleep() and join() methods.
5. Demonstrate inter-thread communication using
wait() and notify().
6. Implement a simple producer-consumer
problem.
7. Create a thread pool using ExecutorService.
⚙️10. Java 8 (Stream API, Lambda, Optional,
Functional Interface)
🔹 Key Programs:
1. Use Stream API to filter even numbers from a
list.
2. Find the maximum and minimum element using
streams.
3. Count occurrences of elements using streams.
4. Sort a list of objects using streams.
5. Convert list to map using streams.
6. Demonstrate Optional usage.
7. Use lambda expressions for functional
interfaces.
8. Create custom functional interface and use
lambda to implement it.
9. Use map() and flatMap() difference with
example.
10. Find duplicate elements in a list using
streams.
🧩 11. Recursion & Patterns
Concepts tested: recursion logic, nested loops
🔹 Questions:
1. Print factorial using recursion.
2. Print Fibonacci series using recursion.
3. Print reverse of a number using recursion.
4. Print sum of digits using recursion.
5. Pattern printing:
o Right triangle
o Inverted triangle
o Pyramid
o Diamond
o Pascal’s triangle
💡 12. Miscellaneous / Advanced
1. Difference between == and .equals() (with
demo).
2. String immutability demo.
3. Singleton class implementation.
4. Clone an object (shallow vs deep copy).
5. Implement Comparable and Comparator.
6. Demonstrate final, finally, and finalize().
7. Reverse a linked list manually.
8. Implement stack and queue using array.
9. Check balanced parentheses using stack.
10. Count occurrence of elements using
HashMap (advanced stream solution).
🧭 13. Real-Time Coding Challenges (asked in tests
like Infosys, TCS NQT, Accenture)
1. Given an array, move all negative numbers to
one side.
2. Find the longest substring without repeating
characters.
3. Find majority element in an array.
4. Find missing and repeating numbers.
5. Rearrange array in alterna ting positive and
negative numbers.
6. Find maximum product subarray.
7. Check if string has balanced brackets.
8. Count number of occurrences of each word in a
paragraph.
9. Implement custom sorting for objects (e.g., sort
Employee by salary).
10. Find pair with given sum in an unsorted
array.
🧭 REAL-TIME TOOLS INTERVIEWS QUESTION.
1. What is JIRA ?
2. What is MAVEN
3.
4.
5.