Java Interview Question
⭐ Human Style Project Explanation (Very Important)
(Project: Axis Bank Net-Banking)
So basically, our project was a Net-Banking Platform for Axis
Bank, which was used to handle secure online transactions.
This system handled transactions from different modules like
Shopping Mall payments and Tax payments.
The main goal of the project was to:
Process user payments securely
Handle OTP verification
Encrypt sensitive data
Store transaction details
Check transaction status
Then we should go for secure transaction flow when handling
banking operations.
⭐ Human Style Architecture Explanation
So basically, the system was built using Java and Spring Boot,
where each functionality was developed as a microservice.
The frontend was developed using Angular, and we used
MySQL and Oracle databases to store transaction data.
All services communicated using REST APIs, and sensitive data
was protected using encryption and decryption.
Then we should go for microservices architecture when we
need scalable and secure systems.
⭐ Human Style SHP Module Flow (Most Important)
So basically, in the Shopping Mall module, when a user selects a
product and clicks Buy Now, the system generates an order request.
This request includes details like order ID, amount, and user details.
Before sending the request to backend,
Then we should go for encryption, because banking data must be
secure.
After receiving the request, the backend decrypts the data and stores
transaction details in the database with status as Pending.
Next, the user selects account type seving/current account and then
receives OTP on registered mobile number.
Then we should go for OTP verification to validate the user.
After successful verification, system performs double verification, such
as fraud check and account validation.
Then the transaction is processed, amount is deducted, and final
transaction status is updated.
Then we should go for secure transaction processing flow.
⭐ Human Style TAX Module Explanation
So basically, the TAX module was used for handling tax payments.
The flow in TAX module was similar to SHP module, including:
Payment request generation
Encryption
OTP verification
Transaction processing
Status update
Then we should go for same secure transaction flow for tax payments.
3️⃣ What was your role in the project?
Answer: My role in the project was mainly backend
development.
My responsibilities included:
Developing REST APIs using Spring Boot
Implementing business logic for banking transactions
Integrating third-party APIs for fraud detection
Writing database queries and optimizing performance
Testing APIs using Postman
Fixing bugs and improving performance
Apart from development, I also did unit testing, API testing using
Postman, and participated in code reviews with SonarQube and Agile
sprint meetings.
I also collaborated with the frontend team and QA team to
ensure smooth functionality.
.
"What challenges did you face?"
Use this:
So basically, one challenge we faced was handling transaction
failures and retry logic.
Sometimes external payment APIs were slow or failed.
Then we should go for retry mechanism and proper error
handling to maintain transaction reliability.
⭐ Add This — Performance Optimization (Very Important)
Say this:
So basically, since this was a real-time banking system,
performance was very important.
Then we should go for:
Database indexing
Optimized queries
Caching where required
To improve response time.
⭐ Add This — Security Explanation (Banking Projects)
Very important in banking.
So basically, security was critical in this project.
Then we should go for:
Encryption and decryption
OTP verification
Token-based authentication
Secure API communication
To protect sensitive financial data.
⭐ Final Closing Line (Strong Ending)
Use this:
So basically, this project helped me gain strong experience in
secure transaction processing, microservices architecture, and
real-time payment systems, and then we should go for secure
and scalable design when building banking applications.
2️⃣ Explain your banking project architecture
Answer:
In my previous project we developed a Net Banking platform
for Axis Bank.
The architecture was based on Microservices architecture.
The system mainly had these components:
1️⃣ Client Layer
Angular based frontend application
Users perform operations like login, fund transfer, balance
check.
2️⃣ API Gateway
All client requests first come to the API Gateway
It routes requests to the appropriate microservice.
3️⃣ Microservices Layer
Different services were implemented as independent services:
Authentication Service → handles login and JWT token
generation
Account Service → manages account details and balance
Transaction Service → processes fund transfers
Notification Service → sends SMS or email alerts
Each service was developed using Spring Boot.
4️⃣ Database Layer
Used MySQL and Oracle databases
Each microservice had its own database.
5️⃣ Third Party Integration
We integrated fraud detection APIs and other banking services
using REST APIs.
6️⃣ Communication
Microservices communicate using REST APIs and JSON
payloads.
2️⃣ Explain your current project (Axis Bank Net Banking
Platform)
Answer:
In my current project, we developed a Net Banking platform for Axis
Bank. The goal of the system was to provide secure and real-time
banking services like account management, balance check, and data
validations, fund transfers,transactions status check .
The system was built using microservices architecture with Java and
Spring Boot. My main responsibility was to develop backend APIs for
account management and transaction processing.
I designed REST APIs and handled high-volume requests. I also
integrated third-party APIs for transaction status check and double
verifications and security validation.
I worked closely with frontend developers using Angular and also
optimized database queries in MySQL and Oracle to improve
performance and reduce response time.
Explain InterMiles Project
Answer:
So basically, InterMiles is an e-commerce platform where users can
purchase different products and earn reward miles for their
purchases.
These reward miles can later be redeemed for offers, discounts, or
other services.
In this project, I mainly worked on backend development using Java
and Spring Boot.
My primary responsibility was to develop REST APIs for different
modules like:
Product management
Order processing
User operations
So basically, in product management, we created APIs to add new
products, update product details, and fetch product information.
Then we should go for product catalog APIs when managing large
numbers of products.
⭐ Order Processing Explanation (InterMiles)
So basically, in the order processing module, when a user selects a
product and places an order, the system generates an order request.
This request includes:
Product details
User details
Quantity
Total amount
After generating the order,
Then we should go for order validation and database to store order
details securely.
Once the order is successfully processed, reward miles are calculated
and credited to the user's account.
3️⃣ What were your responsibilities in the project?
Answer:
My main responsibilities were developing backend services using Java
and Spring Boot. I created REST APIs for different modules like
transactions, account services, and user operations.
I also worked on integrating third-party APIs, writing database queries,
and optimizing performance.
Apart from development, I also did unit testing, API testing using
Postman, and participated in code reviews and Agile sprint meetings.
4) How to integrations in third-party in your project?
In most applications, third-party integration is used when we need to
connect our system with external services like payment
gateways, fraud detection systems, SMS services, or email services.
In my project, we implemented third-party API integration for
payment processing and fraud detection services.
The working process is like this:
First, the third-party provider shares API documentation, which
includes:
API endpoint URL
Request and response format
Authentication method
Required headers and parameters
After that, we should go for creating a service layer in our Spring
Boot application to call those APIs.
For calling the third-party API, we use tools like:
RestTemplate
WebClient
or Feign Client (in microservices)
In my project, the flow worked like this:
1️⃣ User initiates a transaction from the frontend.
2️⃣ The request comes to our backend service (Spring Boot API).
3️⃣ Our service prepares the request payload in JSON format.
4️⃣ Then our system calls the third-party API endpoint using HTTP
POST or GET request.
5️⃣ The third-party service processes the request and sends a
response (success or failure).
6️⃣ We validate the response and update the transaction status in
our database.
7️⃣ Finally, the response is sent back to the frontend application.
For security, we used authentication methods like API keys or
JWT tokens and ensured communication over HTTPS.
This way in my project we integrated third-party services to
extend system functionality without building everything from
scratch.
4️⃣ What challenges did you face in your project?
Answer:
One challenge we faced was handling high transaction volume
during peak times.
Sometimes APIs were taking longer response time.
To solve this:
We optimized database queries
Implemented proper indexing
Improved API response time by optimizing business logic
Used asynchronous processing where required
After these improvements, we were able to reduce latency and
improve system performance.
What is REST API?
Answer:
REST API is a web service that allows communication between
client and server using HTTP protocol.
Common HTTP methods:
GET → retrieve data
POST → create data
PUT → update data
DELETE → delete data
REST APIs usually exchange data in JSON format.
6️⃣ Explain InterMiles Project
Answer:
InterMiles is an e-commerce platform where users can purchase
products and earn reward miles.
In this project I worked on backend services using Java and Spring Boot.
I developed REST APIs for product management, order processing, and
user operations.
I also implemented role-based access control for the admin panel.
Additionally, I optimized MySQL and Oracle database queries to
improve performance for product and order data retrieval.
7️⃣ How do your microservices communicate?
Answer:
In microservices architecture, different services need to communicate
with each other to complete a business operation.
In my project, we mainly used REST APIs for communication
between microservices.
For example, if a user performs a fund transfer, the request first goes
to the API Gateway, and then it calls different microservices like
Account Service, Transaction Service, and Notification Service.
Each service exposes REST endpoints, and other services can call
those APIs using HTTP methods like GET, POST, PUT, and DELETE.
If the communication is simple and requires an immediate response,
we should go for synchronous communication using REST APIs.
But if the process involves background processing or event-based
operations, then we should go for asynchronous communication
using message queues like Kafka .
In my project, most of the communication between services was done
using REST APIs with JSON payloads, and this helped us keep
services loosely coupled and scalable.
8️⃣ How do you secure APIs?
Answer:
We secure APIs using authentication and authorization mechanisms like
JWT tokens.
When a user logs in, the system generates a token which is sent with
every request. The backend validates this token before allowing access
to APIs.
We also use HTTPS and proper input validation to ensure security.
9️⃣ How do you optimize database performance?
Answer:
To optimize database performance we use indexing on frequently
searched columns, avoid unnecessary joins, and write optimized
queries.
We also analyze slow queries and use proper pagination when
retrieving large datasets.
🔟 Why do you want to change your job?
Answer:
I have learned a lot in my current role and worked on multiple projects.
Now I am looking for a new opportunity where I can work on more
challenging systems, improve my backend architecture skills, and grow
technically in a larger environment.
On a scale of 1 to 10, how would you rate yourself in Java, Java
1.8, Spring Boot, and SQL
ANSWERS:
Based on my experience working on real-time projects, I would
rate myself like this:
Java: Around 8 out of 10 because I have good understanding of core
concepts like OOP, collections, multithreading basics, and exception
handling.
Java 1.8: Around 7 out of 10. In my project I have used Streams,
Lambda expressions, and functional interfaces for data
processing.
Spring Boot: Around 8 out of 10 because in my project I
developed multiple REST APIs and microservices using Spring
Boot, and I worked with Spring Data JPA and dependency injection.
SQL: Around 7 out of 10. I have experience writing joins, queries,
stored procedures, and optimizing queries for better
performance using MySQL and Oracle.
Overall, I am comfortable working with these technologies, and I
am continuously improving my knowledge.
Ok let’s start with Core java What is Java?
Java is a high-level, object-oriented, platform-independent
programming language that is widely used for developing
enterprise applications, web applications, and
microservices.
Java follows the principle “Write Once, Run Anywhere”, which
means once we compile the Java program, it can run on any
system that has a Java Virtual Machine (JVM).
Java programs are first compiled into bytecode, and this
bytecode is executed by the JVM, which makes Java platform
independent.
Java also provides many features like object-oriented
programming, automatic memory management through
garbage collection, strong security, and multithreading
support.
Static
What is static in Java?
Answer:Static means class level. It belongs to class, not object.
Why static is used?
Answer:Static is used to share common data among all objects and
save memory.
Can we access static variable without object?
Answer:Yes, we can access using class name.
Example:[Link];
Can static method access non-static variable?
Answer:No, static method cannot access non-static variable directly.
Why main method is static?
Answer:Because JVM calls main method without creating object.
Can static method be overridden?
Answer: No, static variables cannot be overridden in Java.
Because static variables belong to the class level, not to the object
level.
Method overriding happens only with instance methods during runtime
polymorphism
Can static method access instance variables?
Answer No, static methods cannot directly access instance variables.
Because static methods belong to the class, while instance variables
belong to the object.
Since a static method can execute without creating an object, it does
not know which object's instance variable it should access.
If we want to access instance variables inside a static method, we must
create an object of the class.
Why main method is static?
The main method is static because the JVM calls it without creating an
object of the class.
When the program starts execution, the JVM loads the class and
directly calls the main method.
If the main method was not static, the JVM would first need to create an
object of the class, which would make program execution more
complex.
So Java designers made the main method static so that JVM can call it
directly using the class name.
Where are static variables stored?
Static variables are stored in the method area (class memory area)
of the JVM.
When the class is loaded by the class loader, static variables are
created and stored in this memory area.
Since static variables belong to the class, only one copy exists and
it is shared among all objects of that class.
Interview speaking style
So we should go for saying that static variables are stored in the
method area of JVM memory.
Can static method call static method?
Answer:Yes.
Can static method call non-static method?
Answer:No, directly it [Link] is required.
Can static variable have multiple copies?
Answer:No, only one copy exists.
Where static members stored?
Answer:Static members stored in class memory area.
Can you explain One by one Static Execution in class Static
variable, static method, static block, Main method
In Java, static members are executed when the class is loaded into
memory. The execution order is generally:
Static Variables – These are loaded first when the class is loaded.
They belong to the class, not to objects.
Static Block – After static variables, the static block executes. It is
used for initializing static data.
Main Method – After class loading and static initialization, the main()
method starts execution.
Static Methods – These can be called directly using the class
name without creating an object.
Simple order:
Static Variable → Static Block → Main Method → Static
Method (when called)
In my project, static methods are often used for utility
functions that do not require object creation.
Why can't static method access non-static variables?
Because:
In Java, a static method belongs to the class, not to an
object.
Non-static variables belong to individual objects (instances)
of the class.
Since a static method can be executed without creating an
object, it cannot directly access non-static variables.
To access a non-static variable, we must create an object of
the class first.
What Is Instant Block?
Answer:Instance block executes every time when object is created
and used to initialize instance variables.
Flow execution of program
class Test {
// Step 1: Static variable initialization
// When the class is loaded by JVM, static variables are initialized first
public static int num = 10;
// Step 2: Static block executes after static variables
static {
[Link]("Static Block executed: " + num); // prints 10
num = 20; // static variable value updated to 20
}
// Step 4: Instance block executes whenever object is created
{
[Link]("Instance Block executed: " + num);
}
// Step 6: Static method executes only when explicitly called
public static void callStaticMethod() {
[Link]("Static method executed");
[Link]("Static Variable Value: " + num);
}
public static void main(String[] args) {
// Step 3: main method executes after static initialization
[Link]("Main Method Executed");
// Step 4: Object creation → instance block runs
Test test = new Test();
// Step 6: Static method called
callStaticMethod();
// Step 7: Changing static variable value
num = 30;
// Step 8: Creating another object → instance block runs again
Test test2 = new Test();
}
}
OUTPUT= Static Block executed: 10
Main Method Executed
Block executed: 20
Static method executed
Static Variable Value: 20
Block executed: 30
Can you explain OOPS concept
Inheritance (definition, Type)
Inheritance means child class acquire properties to parent class
then we should go for the inheritance.
Type of Inheritance:-
1)Single Inheritance:- one child class inherits from one
parent class.
2)Multilevel Inheritance :- A class inherits from
another class which is already inherited from another
class.
3)Hierarchical Inheritance :- multiple classes inherits
from same parent class.
4)Multiple Inheritance :- does not support in java but
its archived interface.
Abstraction :-
it’s refer to the hiding the internal implementation details
and showing only the essential features of an object the
we should go for abstraction.
Achived using abstract class and Interface.
Encapsulation :-
Binding a data veriable and method in a single unit is
called as encapsulation
How can achieve:- provide public setter and getter
method
so we can read or update the value safely.
Polymorphism
If one Task is performed in different way ,It’s Know as
polymorphisms.
How to achieve:-
There are 2 types:-
Compile time Polymorphism :
Method overloading -is when multiple method in the same class
have same name but different parameter.
Runtime Polymorphism:-
Method Overriding : is one method in the subclass and one
method is superclass.
-same parameter.
-same return type.
-required inheritance.
Interface vs Abstract Class vs Concrete Class
Interface →
If we don’t know anything about the implementation and we only
have the requirement or specification, then we should go for an
interface.
Example:
Servlet
2) Abstract Class →
If we are talking about implementation but not completely
(means partial implementation), then we should go for an
abstract class.
Example:
GenericServlet and HttpServlet
3) Concrete Class →
If we are talking about complete implementation and the class is
ready to provide service, then we should go for a concrete class
Are you aware of Keywords like Final, Static
Yes, in Java, final and static are important keywords.
The final keyword is used to restrict modification — a final
variable cannot be changed, a final method cannot be
overridden, and a final class cannot be inherited.
The static keyword is used for class-level members, meaning it
belongs to the class rather than an object.
In projects, static is commonly used for utility methods, while
final is used for constants or immutable values.
Why can't static method access non-static variables?
Because:
In Java, a static method belongs to the class, not to an
object.
Non-static variables belong to individual objects (instances)
of the class.
Since a static method can be executed without creating an
object, it cannot directly access non-static variables.
To access a non-static variable, we must create an object of
the class first.
Can you explain String class
Ans=> String is an immutable class in Java used to represent a
sequence of characters, and it stores string literals in a String
Pool for memory efficiency
Why is String immutable in Java
Security (used in passwords, URLs, database connections)
Thread-safe (can be shared between threads)
Performance (String Pool memory reuse
What is Difference between == and .equal() in Java
Answer:So basically,
== is used to compare object references (memory location),
while .equals() is used to compare actual content or values of
objects, okay.
Then we should go for .equals() when we want to compare data,
not memory.
🔹 Example:
Integer a = 127;
Integer b = 127;
[Link](a == b); // true
Integer c = 128;
Integer d = 128;
[Link](c == d); // false
🔹 Explanation:
So basically, Java has something called Integer cache (range: -
128 to 127).
For 127 → same object reused → so == is true
For 128 → new objects created → so == is false
Then we should go for .equals() if we want correct value
comparison.
🔹 Correct Way:
[Link]([Link](d)); // true
So basically, .equals() checks value → so it returns true, okay.
Tricky Interview Questions
👉 Q1: Why does == work sometimes and fail sometimes?
So basically, because of Integer caching, not reliable for value
comparison.
👉 Q2: Can .equals() behave like ==?
Yes, okay — if a class does not override .equals(), then it behaves
like ==.
👉 Q3: Difference in String?
String s1 = "abc";
String s2 = "abc";
[Link](s1 == s2); // true
So basically, String uses String pool, so same reference.
But:
String s3 = new String("abc");
[Link](s1 == s3); // false
Then we should go for .equals().
👉 Q4: Which one is faster?
So basically, == is faster (reference check),
but .equals() is correct for value comparison.
What is mean by Call By Value, Call by Reference and Call by
Functions
Call by Value
In call by value, a copy of the variable is passed to the
function.
So, changes made inside the function do not affect the
original value.
Example :
If I send x = 10 to a function, it gets a copy of 10.
Even if the function changes it, x outside stays 10.
Call by Reference
In call by reference, the address of the variable is passed.
So, changes made inside the function affect the original
variable.
Example :
If I send x = 10 by reference, the function works on the same x.
If it changes x to 20, the value outside also becomes 20.
Call by Function
Call by function means one function is called inside another
function, and the returned value is used.
Example :
One function calculates a result, and another function uses that
result.
One-line summary (interview bonus )
Call by Value: Copy is passed → original value not changed
Call by Reference: Address is passed → original value changes
Call by Function: One function calls another function
Have you created Common utility in your project
ANS=>>Yes, I have created common utility classes in my
project.
These utilities are used to avoid code duplication and reuse
common logic across the application.
For example, I created utilities for:
Date and time formatting
Common validation logic
API response handling
Logging and exception handling
String and number conversions
These utility classes were used by multiple modules and
services, which made the code cleaner, reusable, and easier
to maintain
Can you explain Exception Handling means
Type of Exception
How to handle it
Interview Answer
Exception handling is a mechanism to handle runtime errors
so that the application does not crash and continues to work
normally.
Types of Exceptions
Checked Exceptions
These are checked at compile time, and we must
handle them.
Example: IOException, SQLException.
Unchecked Exceptions
These occur at runtime and are usually due to
programming mistakes.
Example: NullPointerException,
ArithmeticException.
Errors
These are serious system issues and usually cannot
be handled.
Example: OutOfMemoryError.
How to Handle Exceptions
We handle exceptions using:
try–catch block to catch the exception
finally block for cleanup
throws to pass exception to caller
throw to create custom exception
Difference between throw and throws keywords
throw
Used to explicitly create and throw an exception
Used inside a method
Used for custom or manual exceptions
Only one exception can be thrown at a time
throws
Used to declare exceptions
Used in method signature
Used to pass responsibility to the calling method
Can declare multiple exceptions.
In my project, we used throw for custom validation exceptions
and throws to propagate checked exceptions like database or IO
errors.
Are you aware of Multithreading Concept
Yes, I am aware of the multithreading concept in Java.
Multithreading is a feature that allows a program to execute multiple
threads simultaneously, which helps in improving application
performance and better CPU utilization.
A thread is basically a lightweight process, and multiple threads can
run within a single program.
For example, in an application we can perform multiple tasks at the
same time, like processing data, sending notifications, and handling
user requests simultaneously.
In Java, multithreading can be implemented in two ways:
1️⃣ By extending the Thread class
2️⃣ By implementing the Runnable interface
Usually we should go for implementing Runnable interface,
because Java does not support multiple inheritance and it provides
better flexibility.
In my project, multithreading was useful when handling multiple
user requests in backend services, where the server processes
multiple API requests concurrently.
Java also provides thread lifecycle management, synchronization,
and thread pools to manage multiple threads efficiently.
What are the Ways to create thread in java
Which is best way to create thread and Why
In Java, there are two main ways to create a thread.
1️⃣ By Extending the Thread Class
In this approach, we create a class that extends the Thread class
and override the run() method.
Then we create the object of that class and call the start()
method.
2️⃣ By Implementing the Runnable Interface
In this approach, we create a class that implements the Runnable
interface and override the run() method.
Then we pass the object of that class to a Thread object.
Which is the Best & Way?
The best way is implementing the Runnable interface.
Reasons
1️⃣ Java does not support multiple inheritance.
If we extend the Thread class, we cannot extend any other class.
2️⃣ Using Runnable provides better code reusability.
3️⃣ It separates the task from the thread execution, which
follows good design principles.
How You Can Say in Interview
You can say:
In Java there are two ways to create a thread: by extending the
Thread class and by implementing the Runnable interface.
Usually we should go for implementing Runnable interface
because Java does not support multiple inheritance and it
provides better flexibility and code reusability.
Can you explain Collection Framework
If we want to represent a group of individual objects as a
single entity, then we should go for the Collection
Framework.
It provides ready-made data structures and algorithms
which help us to perform operations like inserting, deleting,
searching, and sorting data easily.
The Collection Framework is part of the [Link] package.
Main Interfaces in Collection Framework
List – allows duplicate values and maintains insertion order
Example: ArrayList, LinkedList
Set – does not allow duplicate values
Example: HashSet, TreeSet
Queue – follows FIFO order
Example: PriorityQueue
Map – stores data in key–value pairs
Example: HashMap, TreeMap
ArrayList vs LinkedList
So basically:ArrayList: uses dynamic array ,Stores elements in
continuous memory.
its Fast access using index.
ArrayList when: Frequent read operations ,
If you Need to fast random access Then we should go for
ArrayList
LinkedList → uses doubly linked list
Each element is a node
Node contains: data ,next pointer, previous pointer
LinkedList when:
If we need to Frequent insert/delete operations Then we should
go for LinkedList
No need for index-based access
Can you Explain HashMap and how it internally works\
You know How’s changes are done in HashMap in Java 8
What is HashMap?
A HashMap is a class in the Java Collection Framework that is
used to store data in the form of key-value pairs.
In a HashMap:
Keys must be unique
Values can be duplicate
It allows one null key and multiple null values
It does not maintain insertion order
HashMap is part of the [Link] package and it provides very fast
performance for storing and retrieving data.
How HashMap Internally Works
HashMap stores data in key-value pairs and internally works using
hashing where the hashCode of the key determines the bucket
location in an internal array.
first hashCode() of the key is calculated.
When we put a key–value pair into HashMap,
This hash code is converted into an index (bucket) using a hashing
algorithm.
At that bucket index, the value is stored as a Node (Entry).
If two keys have the same index, it is called a collision.
Difference between HashMap and ConcurrentHashMap
HashMap is not thread-safe and is mainly used in single-threaded
environments,
Where as ConcurrentHashMap is thread-safe and used in multi-
threaded applications. ConcurrentHashMap allows multiple
threads to access the map concurrently without locking the entire
map.
Small Real Project Line (Good Impression)
In my project, for shared data in multi-threaded environments we
should go for ConcurrentHashMap instead of HashMap to avoid
concurrency issues.
Difference between HashMap and HashSet
HashMap
Stores data in key–value pairs
Duplicate keys are not allowed, values can be duplicated
Used when we want to store and retrieve values using a key
Allows one null key and multiple null values
👉 Example:
{101=John, 102=Mike}
HashSet
Stores only values, no key–value pair
Duplicate values are not allowed
Used when we want to store unique elements
Allows only one null value
If we try add duplicate key
👉 Example:
[John, Mike]
Internal Working (short point)
HashSet internally uses HashMap
In HashSet, elements are stored as keys in HashMap with a dummy
value
One-line interview summary ⭐
HashMap stores data in key–value pairs, whereas HashSet stores
only unique values.
Real-time project line (bonus)
In my project, we used HashMap for storing user details with IDs as
keys and HashSet to avoid duplicate entries.
What are the features of Java 1.8
Java 1.8 introduced many important features that help developers write cleaner, more
efficient, and functional-style code.
Lambda Expression
Lambda expressions allow us to write short and code for
functional interfaces.
It removes the need for anonymous classes. reduce boilerplate code.
Functional Interface
A Functional Interface is an interface that contains only one
abstract method.
It is mainly used with Lambda Expressions.
Strem API
Stream API is used for processing collections of data in a
functional style.
It allows operations like:
Filtering,sorting,mapping,collecting
Reuse no
Default Methods in Interface
Java 1.8 allows method implementation inside interfaces using
the default keyword.
Method References
Method references provide a shorter way to call methods using
Lambda expressions.
Example: [Link]([Link]::println);
Optional Class
Optional is used to avoid NullPointerException.
Date and Time API
Java 1.8 introduced a new Date and Time API under the package:[Link]
Classes include: LocalDate,LocalTime,LocalDateTime,ZonedDateTime
.map() and FlatMap()
map() and flatMap() – Interview Answer
map()
map() is used to represent one-to-one transformation.
It converts each element into another form.
flatMap()
flatMap() is used to represent one-to-many transformation.
It flattens multiple values into a single stream.
Explain Design pattern
A Design Pattern is a reusable solution to a common problem
in software design.
It provides a standard approach or best practice to solve
frequently occurring design problems in application development.
Design patterns help developers to:
write clean and maintainable code
improve code reusability
make the system more scalable and flexible
Design patterns help to:
Represent best practices
Improve code structure
Reduce tight coupling
What is Singleton Design Pattern?
Answer (Interview Style):
So basically, Singleton Design Pattern is a creational design
pattern.
It is used when we want only one object of a class to be
created in the entire application.
Then we should go for Singleton Design Pattern when:
We need only one instance
We want global access
We want to save memory
Example:
Logger class
Database connection
Spring Bean (Default Singleton Scope)
⭐ Real-Life Example
So basically, think about printer in office.
We don't create multiple printers for each user.
Then we should go for one shared printer, just like Singleton
object.
⭐ Steps to Create Singleton Pattern
So basically, there are 4 steps.
Step 1 — Make Constructor Private
So basically, we make constructor private.
Why?
Because we don't want other classes to create object using new.
Then we should go for private constructor.
private Singleton() {
}
Step 2 — Create Static Instance Variable
So basically, we create static variable of same class.
Why static?
Because static belongs to class, not object.
Then we should go for static instance variable.
private static Singleton instance;
Step 3 — Create Public Static Method
So basically, we create method to return object.
This method checks:
If object is null → create object
Else → return existing object
Then we should go for getInstance() method.
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
Step 4 — Use Singleton Object
So basically, we call getInstance() method.
Then we should go for same object every time.
⭐ Complete Singleton Example
class Singleton {
// Step 2: static instance
private static Singleton instance;
// Step 1: private constructor
private Singleton() {
[Link]("Object Created");
}
// Step 3: public static method
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class SingletonMain {
public static void main(String[] args) {
// Step 4: calling method
Singleton obj1 = [Link]();
Singleton obj2 = [Link]();
[Link](obj1 == obj2);
}
}
Output:
Object Created
true
So basically, object created only once.
Then we should go for Singleton Pattern.
What is Factory Design Pattern?
Interview Style Answer:
So basically, Factory Design Pattern is a creational design
pattern.
It is used to create objects without exposing the object
creation logic to the client.
Instead of creating object using new keyword directly, we create
object using factory method.
Then we should go for Factory Design Pattern when:
Object creation logic is complex
We don't want client to know exact class
We want loose coupling
⭐ Real-Life Example
So basically, think about Restaurant.
You order:👉 "Pizza"
You don't cook pizza yourself.
Restaurant kitchen creates pizza and gives to you.
Then we should go for Factory, where:
Customer → Client
Kitchen → Factory
Pizza → Object
⭐ Problem Without Factory Pattern
So basically, without factory, client creates object directly.
Circle circle = new Circle();
Rectangle rectangle = new Rectangle();
Problem:
Client knows all classes
Code becomes tightly coupled
Difficult to change later
Then we should go for Factory Pattern to remove tight coupling.
⭐ Steps to Implement Factory Pattern
So basically, there are 4 steps.
Step 1 — Create Interface (Common Type)
So basically, we create interface.
All classes will implement this.
Then we should go for common interface.
interface Shape {
void draw();
Step 2 — Create Implementation Classes
So basically, create multiple classes implementing interface.
Then we should go for different object types.
class Circle implements Shape {
public void draw() {
[Link]("Drawing Circle");
}
}
class Rectangle implements Shape {
public void draw() {
[Link]("Drawing Rectangle");
}
}
Step 3 — Create Factory Class
So basically, create class that returns object based on input.
Then we should go for Factory Class.
class ShapeFactory {
public static Shape getShape(String type) {
if ([Link]("circle")) {
return new Circle();
}
if ([Link]("rectangle")) {
return new Rectangle();
}
return null;
}
}
Step 4 — Use Factory in Main Method
So basically, client calls factory method instead of new.
Then we should go for factory method call.
⭐ Complete Factory Pattern Example
interface Shape {
void draw();
}
// Step 2
class Circle implements Shape {
public void draw() {
[Link]("Drawing Circle");
}
}
class Rectangle implements Shape {
public void draw() {
[Link]("Drawing Rectangle");
}
}
// Step 3
class ShapeFactory {
public static Shape getShape(String type) {
if ([Link]("circle")) {
return new Circle();
}
if ([Link]("rectangle")) {
return new Rectangle();
}
return null;
}
}
// Step 4
public class FactoryMain {
public static void main(String[] args) {
Shape shape1 = [Link]("circle");
[Link]();
Shape shape2 = [Link]("rectangle");
[Link]();
}
}
Output:
Drawing Circle
Drawing Rectangle
So basically, client doesn't know which class object is created.
Then we should go for Factory Pattern.
⭐ Real-Time Example (Very Important for Interview)
So basically, Spring uses Factory Pattern internally.
Example:
BeanFactory
Spring creates objects using BeanFactory.
Then we should go for Factory Pattern in:
Spring Bean creation
Logger creation
Database driver selection
Example:
ApplicationContext context = new
ClassPathXmlApplicationContext("[Link]");
UserService user = [Link]([Link]);
So basically, Spring creates object using factory.
Then we should go for Factory Pattern.
Types of Design Patterns
1) Creational Design Pattern
Used to represent object creation logic.
Example: Singleton, Factory
2) Structural Design Pattern
Used to represent relationships between classes.
Example: Adapter, Facade
3) Behavioral Design Pattern
Used to represent communication between objects.
Example: Observer, Strategy
One-line interview summary ⭐
Design patterns are standard solutions used to represent best
practices for solving common design problems in software
applications.
Real-time Project Line (bonus)
In my project, we used Singleton for database connections
and Factory pattern for object creation.
Can you explain Optional Class
Explain Optional Class – Interview Answer
The Optional class in Java 8 is used to represent a value that
may or may not be present.
It helps to avoid NullPointerException by providing a safe way to
handle null values.
Why Optional is used
To represent optional values
To avoid null checks
To write cleaner and safer code
How Optional works (simple)
If value is present → Optional contains the value
If value is absent → Optional is empty
Common Methods
of() → used when value is not null
ofNullable() → used when value may be null
isPresent() → checks if value exists
orElse() → provides default value
One-line interview summary ⭐
Optional class is used to represent optional values and avoid
NullPointerException in Java 8.
Real-time Project Line (bonus)
In my project, we used Optional to handle null responses from
database and APIs safely.
SQL:-
27) Difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL
OUTER JOIN
INNER JOIN
Returns only matching records from both tables
👉 Meaning:
Common data from both tables
LEFT JOIN
Returns all records from left table
Matching records from right table
If no match → NULL
👉 Meaning:
Left table data is important
RIGHT JOIN
Returns all records from right table
Matching records from left table
If no match → NULL
👉 Meaning:
Right table data is important
FULL OUTER JOIN
Returns all records from both tables
Matching + non-matching rows
👉 Meaning:
Complete data from both tables
One-line summary ⭐
INNER JOIN gives matching data, LEFT and RIGHT JOIN give all data from
one side, and FULL JOIN gives all data from both sides.
28) How would you optimize a slow-performing query?
To optimize a slow query, I would:
Use proper indexes
Avoid SELECT *, fetch only required columns
Use WHERE clause to filter data early
Check JOIN conditions
Use EXPLAIN plan to analyze query
Avoid unnecessary subqueries
Use LIMIT if possible
One-line summary ⭐
Query optimization is done by using indexes, proper joins, filtering data,
and analyzing execution plans.
29) What is Index?
An index is a database object used to speed up data retrieval.
👉 Simple meaning:
Index works like a book index, helping the database find data faster.
Advantages
Improves SELECT performance
Faster search and filtering
Disadvantage
Slows down INSERT, UPDATE, DELETE
One-line summary ⭐
Index is used to improve query performance by speeding up data access.
30) Difference between WHERE and HAVING
WHERE
Used to filter rows
Works before GROUP BY
Cannot use aggregate functions
HAVING
Used to filter groups
Works after GROUP BY
Used with aggregate functions
Example meaning
WHERE → filter individual records
HAVING → filter grouped records
One-line summary ⭐
WHERE filters rows, HAVING filters groups.
31) How do you find the second highest salary from Employee
table?
Using Subquery
SELECT MAX(salary) FROM Employee WHERE salary < (SELECT
MAX(salary) FROM Employee);
One-line explanation
First we find the highest salary, then we find the maximum salary less
than that.
Hibernate :-
27) Difference between get() and load() in Hibernate
get()
Fetches data immediately
Returns null if record not found
Hits the database immediately
Used when we are not sure data exists
👉 Example meaning:
It goes to DB and gets the data right away.
load()
Fetches data lazily
Returns proxy object
Hits DB only when data is accessed
Throws ObjectNotFoundException if record not found
👉 Example meaning:
It creates a reference and fetches data when needed.
One-line interview summary ⭐
get() fetches data immediately and returns null if not found,
whereas load() fetches data lazily and throws exception if data does
not exist.
28) How is Hibernate different from ORM and JPA?
ORM (Object Relational Mapping)
It is a concept
Used to map Java objects to database tables
Not a tool or framework
👉 Meaning:
ORM defines what we want to achieve.
JPA (Java Persistence API)
It is a specification
Defines rules and annotations for ORM
Does not provide implementation
👉 Meaning:
JPA defines how ORM should be done.
Spring Boot :-
8️⃣ What is Spring Boot?
Answer:Spring Boot is a framework built on top of Spring Framework
that helps to develop production-ready applications quickly.
Main advantages:Auto configuration
Embedded server (Tomcat)
Minimal configuration
Faster development
It is widely used for microservices development.
Can you explain Difference Between Spring and Spring Boot
The main difference between Spring Framework and Spring Boot
is configuration and ease of development.
Spring requires manual configuration and setup, while Spring
Boot provides auto-configuration and embedded servers like
Apache Tomcat.
Because of this, Spring Boot helps developers build and run
applications faster with minimal configuration.
In my project, when we want to develop REST APIs quickly, we
prefer using Spring Boot.
What happens internally when you start a Spring Boot
application?
Answer:
So basically, when we run the application:
[Link]() is called
Then we should go for creating ApplicationContext
Auto-configuration starts based on dependencies
Beans are created and managed
Embedded server (Tomcat) starts
Okay, finally application is ready to serve requests.
Explain Inversion of Control (IoC) and Dependency Injection
(DI).
In Spring Framework, Inversion of Control (IoC) means the
control of object creation and lifecycle is handled by the Spring IoC
Container instead of the developer.
Dependency Injection (DI) is the technique used to achieve IoC,
where the container injects required dependencies into a class
automatically.
This reduces tight coupling and improves code
maintainability.
In my project, we use DI to inject service classes into
controllers using annotations like @Autowired.
What are the different types of Dependency Injection in
Spring?
In Spring Framework, there are mainly two types of
Dependency Injection: Constructor Injection and Setter
Injection.
Constructor Injection is used when dependencies are provided
through the class constructor, while Setter Injection uses setter
methods to inject dependencies.
Constructor Injection is generally recommended because it
ensures mandatory dependencies are provided.
In my project, we mostly use Constructor Injection in Spring
Boot services for better code design.
How does Spring Boot Auto-Configuration work?
In Spring Boot, Auto-Configuration automatically configures the
application based on the dependencies present in the project
classpath. It is enabled using the @EnableAutoConfiguration
annotation, which is included in @SpringBootApplication.
For example, if Apache Tomcat and web dependencies are present,
Spring Boot automatically configures a web server.
This reduces manual configuration and speeds up
development in projects built with the Spring Framework.
Explain the difference between @Controller and
@RestController.
In Spring Framework, @Controller is used to create web
controllers that return view pages like JSP or HTML.
@RestController is used to build REST APIs that return data in
JSON or XML format.
@RestController is basically a combination of @Controller and
@ResponseBody.
In my project using Spring Boot, we mostly use @RestController to
create RESTful web services.
How does Spring Security work?
Spring Security is used to provide authentication and
authorization in applications built with Spring Boot and the
Spring Framework.
It works by using security filters that intercept incoming HTTP
requests and check user credentials.
After authentication, it verifies whether the user has the required
roles or permissions to access the resource.
In my project, we use Spring Security to secure REST APIs and
protect endpoints from unauthorized access. 🔐
How do you implement JWT-based authentication in Spring
Boot?
In Spring Boot, JWT authentication is implemented using JSON
Web Token along with Spring Security.
First, the user logs in with credentials, and the server generates a
JWT token after successful authentication.
This token is sent in the Authorization header with every request.
In my project, we validate the JWT token using a filter, and if the
token is valid, the user is allowed to access the secured APIs. 🔐
What is the purpose of OAuth2 in Spring Security?
OAuth 2.0 in Spring Security is used for secure authorization
without sharing user credentials.
It allows applications to access resources on behalf of a user
using access tokens.
For example, users can log in using external providers like Google
or GitHub.
In my Spring Boot project, OAuth2 can be used to implement
social login and secure API access. 🔐
How do you secure REST APIs in Spring Boot?
In Spring Boot, REST APIs are secured using Spring Security.
We configure authentication and authorization to control access to
API endpoints.
Commonly, we use JSON Web Token (JWT) for token-based
authentication to validate each request.
In my project, we secure APIs by adding security filters,
validating JWT tokens, and restricting endpoints based on
user roles. 🔐
What if two beans of same type exist?
Answer:So basically, Spring will throw
NoUniqueBeanDefinitionException.
@Component vs @Bean (Deep Explanation)
✅ Basic Answer So basically:
@Component → auto-detected via component scanning
@Bean → manually defined inside @Configuration class
Then we should go for @Bean when we don’t have control over the class,
okay.
🔹 1) How @Component Works Internally
Answer:
So basically, @Component works with **@ComponentScan`.
Then we should go for:
Spring scans packages
Finds classes with @Component, @Service, @Repository
Automatically creates beans in IOC container
🔹 Example:
@Component
public class MyService {
}
So basically, no need to write extra configuration, Spring will handle it,
okay.
🔹 2) How @Bean Works Internally
Answer:
So basically, @Bean is used inside a @Configuration class.
Then we should go for manually creating object and returning it to Spring
container.
🔹 Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
So basically, Spring will call this method and register the object as bean,
okay.
Programs:
Ex. “SURESH PIMPARKAR” Number of occurrences in Sting
import [Link];
import [Link];
public class CharaterCount {
public static void main(String[] args) {
String str = "SURESH PIMPARKAR";
str = [Link](" ", "");
Map<Character, Integer> map = new
HashMap<>();
for (char c : [Link]()) {
if ([Link](c)) {
[Link](c, [Link](c) + 1);
} else {
[Link](c, 1);
}
}
[Link](map);
}
}
Logic Explanation (How you can explain in interview)
1️
⃣ First we take a String "SURESH PIMPARKAR".
2️
⃣ We remove spaces using replace().
3️
⃣ Then we create a HashMap to store character as key
and occurrence count as value.
4️
⃣ We convert the string to character array using
toCharArray().
5️
⃣ Then we loop through each character.
If the character already exists in the map → increase the
count.
Otherwise → insert the character with value 1.
6️
⃣ Finally we print the map containing character
frequencies.
Java 8 using ===
import [Link];
import [Link];
import [Link];
public class CharaterCount {
public static void main(String[] args) {
String str= "SURESH PIMPARKAR".replace("", "");
Map<Character, Long>result =[Link]()
.mapToObj(c ->(char)c)
.collect([Link]([Link]
ity()
,[Link]()));
[Link]("Test Result"+result);
}
}
Re-arrange based on the position provided as parameter
input1: {1,3,5,7}
input2: 3
outputs: {5,1,3,7}
import [Link].*;
import [Link];
import [Link].*;
public class RearrangeArray {
public static void main(String[] args) {
Integer[] arr = {1,3,5,7};
int positionOfArray=3;
List<Integer>list =new ArrayList<>([Link](arr));
int element =[Link](positionOfArray-1);
[Link](0,element);
[Link]("Rearrange ArrayList:"+list);
}
}
Rearrange ArrayList:[5, 1, 3, 7]
First I converted the array into an ArrayList to perform dynamic
operations. Then I removed the element at the given position using
remove(position-1) because Java uses zero-based indexing. After
removing the element, I inserted it at index 0 using add(0,
element), which rearranges the array as required
Find the Second highest number in java
public class SecondHighest {
public static void main(String[] args) {
int arr[] = {10, 20, 30, 40, 50};
int high=Integer.MIN_VALUE;
int secHigh=Integer.MIN_VALUE;
for (int number :arr){
if(number >high) {
secHigh=high;
high = number;}
else if(number >secHigh && number !=high) {
secHigh=number;
}
}
[Link]("Second High Number is :"+secHigh);
}
}
1️⃣ Java Program: Find Repeated Numbers in an Array using HashMap
Solution:
import [Link];
import [Link];
public class RepeatedNumber {
public static void main(String[] args) {
int arr[] = {1,2,3,4,2,5,3,6,1};
HashMap<Integer, Integer> map = new HashMap<>();
for(int num : arr) {
if([Link](num)) {
[Link](num, [Link](num) + 1);
} else {
[Link](num, 1);
}
}
[Link]("Repeated Numbers:");
for([Link]<Integer,Integer> entry : [Link]()) {
if([Link]() > 1) {
[Link]([Link]());
}
}
}
}
1️⃣ Find Duplicate Elements in Array
✔ Core Java Version
import [Link].*;
public class FindDuplicatesCore {
public static void main(String[] args) {
int[] arr = {1,2,3,4,2,5,3};
Set<Integer> set = new HashSet<>();
for (int num : arr) {
if () {
[Link]("Duplicate: " + num);
}
}
}
}
✔ Java 8 Version
import [Link].*;
public class FindDuplicatesStream {
public static void main(String[] args) {
List<Integer> list =
[Link](1,2,3,4,2,5,3);
Set<Integer> seen = new HashSet<>();
[Link]()
.filter(n -> )
.forEach(n ->
[Link]("Duplicate: " + n));
}
}
2️⃣ Find Second Highest Number✔ Core Java Version
public class SecondHighestCore {
public static void main(String[] args) {
int[] arr = {10,20,30,40,50};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
[Link]( "Second Highest: " + second);
}
}
✔ Java 8 Version
import [Link].*;
public class SecondHighestStream {
public static void main(String[] args) {
List<Integer> list = [Link](10,20,30,40,50);
Integer result = [Link]()
.sorted([Link]())
.skip(1)
.findFirst()
.get();
[Link](
"Second Highest: " + result);
}
}
3️⃣ First Non-Repeated Character
✔ Core Java Version
import [Link].*;
public class FirstNonRepeatedCore {
public static void main(String[] args) {
String str = "swiss";
Map<Character,Integer> map =
new LinkedHashMap<>();
for (char c : [Link]()) {
[Link](c,
[Link](c,0) + 1);
}
for (char c : [Link]()) {
if ([Link](c) == 1) {
[Link](
"First Non-Repeated: " + c);
break;
}
}
}
}
✔ Java 8 Version
import [Link].*;
import [Link].*;
public class FirstNonRepeatedStream {
public static void main(String[] args) {
String str = "swiss";
Character result =
[Link]()
.mapToObj(c -> (char)c)
.collect([Link](
c -> c,
LinkedHashMap::new,
[Link]()
))
.entrySet()
.stream()
.filter(e -> [Link]() == 1)
.map([Link]::getKey)
.findFirst()
.get();
[Link](
"First Non-Repeated: " + result);
}
}
4️⃣ Reverse Words in Sentence
✔ Core Java Version
public class ReverseWordsCore {
public static void main(String[] args) {
String str = "Java is powerful";
String[] words = [Link](" ");
for (int i = [Link] - 1;
i >= 0; i--) {
[Link](
words[i] + " ");
}
}
}
✔ Java 8 Version
import [Link].*;
public class ReverseWordsStream {
public static void main(String[] args) {
String str = "Java is powerful";
String result =
[Link]([Link](" "))
.reduce((a,b) ->
b + " " + a)
.get();
[Link](result);
}
}
5️⃣ Count Frequency of Characters
✔ Core Java Version
import [Link].*;
public class CharacterFrequencyCore {
public static void main(String[] args) {
String str = "programming";
Map<Character,Integer> map =
new HashMap<>();
for (char c : [Link]()) {
[Link](c,
[Link](c,0) + 1);
}
[Link](map);
}
}
✔ Java 8 Version
import [Link].*;
import [Link].*;
public class CharacterFrequencyStream {
public static void main(String[] args) {
String str = "programming";
Map<Character,Long> map =
[Link]()
.mapToObj(c -> (char)c)
.collect([Link](
c -> c,
[Link]()
));
[Link](map);
}
}
6️⃣ Find Missing Number in Array
✔ Core Java Version
public class MissingNumberCore {
public static void main(String[] args) {
int[] arr = {1,2,3,5};
int n = 5;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
int missing = expectedSum - actualSum;
[Link]( "Missing Number: " + missing);
}
}
✔ Java 8 Version
import [Link].*;
public class MissingNumberStream {
public static void main(String[] args) {
int[] arr = {1,2,3,5};
int n = 5;
int expectedSum = n * (n + 1) / 2;
int actualSum =
[Link](arr).sum();
int missing =
expectedSum - actualSum;
[Link](
"Missing Number: " + missing);
}
}