Top Java Interview Questions by Topic
Core Java
1. What is the difference between JDK, JRE, and JVM?
JDK is the Java Development Kit for coding and compiling.
JRE is the Java Runtime Environment for running Java apps.
JVM is the Java Virtual Machine that executes bytecode.
2. What are access modifiers in Java?
Access modifiers control visibility: public, private, protected, and default.
They define where a class, method, or variable can be accessed.
Use them to enforce encapsulation and security.
3. What is the difference between == and equals()?
== checks reference equality (same object in memory).
equals() checks value/content equality.
Override equals() for custom object comparison.
4. What is a constructor in Java?
A constructor initializes a new object.
It has the same name as the class and no return type.
You can overload constructors for different initializations.
5. What is the difference between static and non-static methods?
Static methods belong to the class, not objects.
They can be called without creating an instance.
Non-static methods need an object to be called.
6. What is the final keyword in Java?
final can be used with variables, methods, or classes.
A final variable cannot be changed, a final method cannot be overridden, and a final class
cannot be extended.
It ensures immutability or restriction.
7. What is method overloading and overriding?
Overloading: same method name, different parameters in the same class.
Overriding: same method name and parameters in child class.
Overloading is compile-time, overriding is runtime.
8. What is the difference between Array and ArrayList?
Array is fixed-size and can store primitives or objects.
ArrayList is dynamic and stores only objects.
ArrayList provides more flexible operations.
9. What is the use of the 'this' keyword?
'this' refers to the current object instance.
It is used to resolve variable shadowing and call other constructors.
Helps in method chaining.
10. What is a package in Java?
A package groups related classes and interfaces.
It helps organize code and avoid name conflicts.
Use 'import' to access classes from packages.
OOPs (Object-Oriented Programming)
1. What are the four main OOP principles?
Encapsulation, Inheritance, Polymorphism, and Abstraction.
They help organize and structure code.
Promote code reuse and flexibility.
2. What is encapsulation?
Encapsulation hides data using private variables.
Access is provided via public getters and setters.
It protects data and maintains control.
3. What is inheritance?
Inheritance allows a class to inherit properties from another class.
The 'extends' keyword is used for inheritance.
It promotes code reuse.
4. What is polymorphism?
Polymorphism means one interface, many implementations.
It allows method overriding and overloading.
Enables dynamic method dispatch.
5. What is abstraction?
Abstraction hides complex details and shows only essentials.
Achieved using abstract classes and interfaces.
Simplifies code and increases security.
6. What is an interface in Java?
An interface defines abstract methods (no body).
A class implements an interface to provide method bodies.
Supports multiple inheritance.
7. What is the difference between abstract class and interface?
Abstract class can have method bodies and variables.
Interface has only abstract methods (Java 8+ allows default/static methods).
A class can implement multiple interfaces but extend only one class.
8. What is method overriding?
Child class provides its own implementation of a parent class method.
Method signature must be the same.
Used for runtime polymorphism.
9. What is constructor chaining?
Calling one constructor from another in the same class using 'this()'.
Or from parent class using 'super()'.
Helps reuse initialization code.
10. What is the use of 'super' keyword?
'super' refers to the parent class object.
Used to access parent class methods and variables.
Also used to call parent class constructor.
Exception Handling
1. What is exception handling in Java?
Exception handling manages runtime errors.
Uses try, catch, finally, and throw/throws.
Prevents program crashes and handles errors gracefully.
2. What is the difference between checked and unchecked exceptions?
Checked exceptions are checked at compile time (e.g., IOException).
Unchecked exceptions are checked at runtime (e.g., NullPointerException).
Checked exceptions must be handled or declared.
3. What is the use of finally block?
finally always executes after try/catch.
Used for cleanup code like closing resources.
Runs even if an exception occurs or return is called.
4. What is the difference between throw and throws?
throw is used to explicitly throw an exception.
throws is used in method signature to declare exceptions.
throw is inside method, throws is in method declaration.
5. What is try-with-resources?
Introduced in Java 7 for automatic resource management.
Resources like streams are closed automatically.
Use with classes implementing AutoCloseable.
6. What is custom exception?
A user-defined exception class extending Exception or RuntimeException.
Used for application-specific error handling.
Helps provide meaningful error messages.
7. What happens if an exception is not caught?
The program terminates abnormally.
The JVM prints a stack trace.
Resources may not be released.
8. Can you catch multiple exceptions in a single catch block?
Yes, using multi-catch (Java 7+).
Separate exception types with '|'.
Reduces code duplication.
9. What is the difference between Error and Exception?
Error indicates serious problems (e.g., OutOfMemoryError).
Exception is for recoverable conditions.
Errors should not be caught, exceptions can be.
10. What is stack trace?
A stack trace shows the call sequence when an exception occurs.
Helps debug the source of the error.
Printed by JVM or can be logged.
Collections
1. What is the Java Collections Framework?
A set of interfaces and classes for storing and manipulating groups of data.
Includes List, Set, Map, and Queue.
Provides algorithms like sorting and searching.
2. What is the difference between List and Set?
List allows duplicates and maintains order.
Set does not allow duplicates and may not maintain order.
Examples: ArrayList (List), HashSet (Set).
3. What is the difference between HashMap and Hashtable?
HashMap is not synchronized, allows null keys/values.
Hashtable is synchronized, does not allow null keys/values.
HashMap is faster, Hashtable is thread-safe.
4. What is the difference between ArrayList and LinkedList?
ArrayList is backed by an array, fast for random access.
LinkedList is backed by nodes, fast for insert/delete.
Choose based on usage pattern.
5. What is Iterator in Java?
Iterator is used to traverse collections.
Provides methods like hasNext(), next(), and remove().
Supports safe removal during iteration.
6. What is the difference between Comparable and Comparator?
Comparable is for natural ordering, implemented by the class.
Comparator is for custom ordering, implemented separately.
Used in sorting collections.
7. What is fail-fast and fail-safe iterator?
Fail-fast throws ConcurrentModificationException on modification.
Fail-safe works on a copy, no exception thrown.
Fail-fast: ArrayList, fail-safe: CopyOnWriteArrayList.
8. What is Map in Java?
Map stores key-value pairs.
Keys are unique, values can be duplicate.
Examples: HashMap, TreeMap.
9. How to synchronize a collection?
Use [Link]() or synchronized blocks.
Or use concurrent collections like ConcurrentHashMap.
Ensures thread safety.
10. What is the difference between HashSet and TreeSet?
HashSet is unordered, faster, uses hashing.
TreeSet is ordered (sorted), slower, uses Red-Black tree.
Choose based on need for sorting.
Multithreading
1. What is a thread in Java?
A thread is a lightweight process for multitasking.
Java supports threads via Thread class and Runnable interface.
Threads run concurrently.
2. How to create a thread in Java?
Extend Thread class or implement Runnable interface.
Override run() method with thread logic.
Start thread using start() method.
3. What is synchronization?
Synchronization controls access to shared resources.
Prevents data inconsistency in multithreaded code.
Use synchronized keyword or blocks.
4. What is the difference between process and thread?
Process is an independent program with its own memory.
Thread is a part of a process, shares memory.
Threads are lightweight, processes are heavy.
5. What is deadlock?
Deadlock is when two or more threads wait forever for each other.
Occurs due to circular resource holding.
Avoid by proper locking order.
6. What is volatile keyword?
volatile ensures visibility of changes to variables across threads.
Prevents caching of variable values.
Used for flags and shared data.
7. What is thread-safe code?
Thread-safe code works correctly when accessed by multiple threads.
Achieved using synchronization, locks, or concurrent classes.
Prevents race conditions.
8. What is ExecutorService?
ExecutorService manages thread pools.
Provides methods to submit and manage tasks.
Improves thread management and performance.
9. What is the difference between wait() and sleep()?
wait() releases the lock and waits for notify().
sleep() pauses thread but does not release lock.
wait() is for inter-thread communication.
10. What is Callable and Future?
Callable is like Runnable but returns a result.
Future represents the result of an asynchronous computation.
Used with ExecutorService for parallel tasks.
Java 8
1. What are lambda expressions?
Lambda expressions provide a concise way to write anonymous functions.
Syntax: (parameters) -> expression.
Used mainly with functional interfaces.
2. What are functional interfaces?
An interface with a single abstract method.
Examples: Runnable, Callable, Comparator.
Used with lambda expressions.
3. What is Stream API?
Stream API processes collections in a functional style.
Supports operations like filter, map, reduce.
Enables parallel and sequential processing.
4. What is Optional class?
Optional is a container for nullable values.
Helps avoid NullPointerException.
Provides methods like isPresent(), get(), orElse().
5. What are default methods in interfaces?
Default methods have a body in interfaces.
Allow adding new methods without breaking existing code.
Use 'default' keyword.
6. What is method reference?
Method reference is a shorthand for calling methods.
Syntax: ClassName::methodName.
Used with functional interfaces.
7. What is the difference between map() and flatMap()?
map() transforms each element, returns a stream of results.
flatMap() flattens nested streams into a single stream.
Used for complex data transformations.
8. What is the purpose of forEach()?
forEach() iterates over each element in a collection or stream.
Accepts a lambda expression or method reference.
Simplifies iteration.
9. What is the significance of Predicate interface?
Predicate represents a boolean-valued function.
Used for filtering in streams.
Has methods like test(), and(), or().
10. How to create an immutable list in Java 8?
Use [Link]() or [Link]() (Java 9+).
Prevents modification after creation.
Ensures thread safety and consistency.
JDBC
1. What is JDBC?
JDBC stands for Java Database Connectivity.
It is an API to connect and interact with databases.
Supports executing SQL queries from Java.
2. What are the main steps in JDBC?
Load driver, establish connection, create statement, execute query, process results, close
connection.
Each step is essential for database operations.
Use try-with-resources for cleanup.
3. What is a PreparedStatement?
PreparedStatement is a precompiled SQL statement.
Prevents SQL injection and improves performance.
Supports parameterized queries.
4. What is the difference between Statement and PreparedStatement?
Statement is for simple, static queries.
PreparedStatement is for dynamic, parameterized queries.
PreparedStatement is safer and faster.
5. How to handle transactions in JDBC?
Use setAutoCommit(false) to start a transaction.
Commit or rollback as needed.
Ensures data consistency.
6. What is ResultSet in JDBC?
ResultSet holds data returned by a query.
Provides methods to read data row by row.
Use next(), getString(), getInt(), etc.
7. How to prevent SQL injection in JDBC?
Use PreparedStatement with parameterized queries.
Avoid concatenating user input in SQL.
Validates and escapes input.
8. What is connection pooling?
Connection pooling reuses database connections.
Improves performance and resource usage.
Managed by libraries like HikariCP or Apache DBCP.
9. How to close JDBC resources?
Always close ResultSet, Statement, and Connection.
Use try-with-resources for automatic closing.
Prevents resource leaks.
10. What is batch processing in JDBC?
Batch processing executes multiple queries in one go.
Use addBatch() and executeBatch() methods.
Improves performance for bulk operations.
Spring Boot
1. What is Spring Boot?
Spring Boot simplifies Spring application setup.
Provides auto-configuration and embedded servers.
Reduces boilerplate code.
2. What is @SpringBootApplication annotation?
It is a combination of @Configuration, @EnableAutoConfiguration, and @ComponentScan.
Marks the main class of a Spring Boot app.
Enables auto-configuration and component scanning.
3. How to create REST API in Spring Boot?
Use @RestController and @RequestMapping annotations.
Define endpoints as methods.
Return data as JSON or XML.
4. What is [Link]?
A file for externalizing configuration.
Stores settings like port, database URL, etc.
Supports environment-specific profiles.
5. What is dependency injection in Spring Boot?
Spring injects dependencies automatically using @Autowired.
Promotes loose coupling and easier testing.
Supports constructor and field injection.
6. What is the use of @Component, @Service, @Repository?
They mark classes as Spring-managed beans.
@Component is generic, @Service for business logic, @Repository for data access.
Enable component scanning.
7. How to handle exceptions in Spring Boot?
Use @ControllerAdvice and @ExceptionHandler.
Centralizes exception handling.
Returns custom error responses.
8. What is actuator in Spring Boot?
Actuator provides production-ready features.
Includes health checks, metrics, and monitoring endpoints.
Enable with spring-boot-starter-actuator.
9. How to connect Spring Boot to a database?
Configure datasource in [Link].
Use Spring Data JPA or JDBC templates.
Spring Boot auto-configures database beans.
10. What is starter dependency in Spring Boot?
Starter dependencies bundle common libraries.
Example: spring-boot-starter-web for web apps.
Simplifies dependency management.
Spring MVC
1. What is Spring MVC?
Spring MVC is a web framework for building web applications.
Follows Model-View-Controller pattern.
Separates business, presentation, and navigation logic.
2. What is DispatcherServlet?
Central controller in Spring MVC.
Routes requests to appropriate controllers.
Configured in [Link] or auto-configured in Spring Boot.
3. What are @Controller and @RestController?
@Controller handles web requests and returns views.
@RestController returns data (JSON/XML) directly.
@RestController = @Controller + @ResponseBody.
4. What is @RequestMapping?
Maps HTTP requests to handler methods.
Can specify URL, HTTP method, headers, etc.
Supports flexible routing.
5. How to handle form data in Spring MVC?
Use @ModelAttribute or @RequestParam in controller methods.
Bind form fields to Java objects.
Supports validation and data binding.
6. What is ModelAndView?
ModelAndView holds model data and view name.
Returned by controller methods.
Used for rendering views with data.
7. How to validate user input in Spring MVC?
Use @Valid or @Validated annotations.
Define validation rules in model classes.
Handle errors with BindingResult.
8. What is view resolver?
View resolver maps view names to actual views (JSP, Thymeleaf).
Configured in application context.
Controls how views are rendered.
9. What is Interceptor in Spring MVC?
Interceptor intercepts requests before reaching controllers.
Used for logging, authentication, etc.
Implement HandlerInterceptor interface.
10. How to handle exceptions globally in Spring MVC?
Use @ControllerAdvice with @ExceptionHandler methods.
Handles exceptions across all controllers.
Returns custom error responses.
Microservices
1. What are microservices?
Microservices are small, independent services.
Each service handles a specific business function.
They communicate over APIs.
2. What are the benefits of microservices?
Improved scalability and flexibility.
Independent deployment and development.
Easier maintenance and fault isolation.
3. How do microservices communicate?
Via REST APIs, messaging queues, or gRPC.
Use HTTP, AMQP, or other protocols.
Ensures loose coupling.
4. What is service discovery?
Service discovery locates services dynamically.
Tools like Eureka or Consul are used.
Enables load balancing and failover.
5. What is API Gateway?
API Gateway is a single entry point for clients.
Handles routing, authentication, and rate limiting.
Examples: Zuul, Spring Cloud Gateway.
6. What is circuit breaker pattern?
Prevents cascading failures in microservices.
Stops calls to a failing service temporarily.
Implemented using Hystrix or Resilience4j.
7. How to handle configuration in microservices?
Use centralized config servers (e.g., Spring Cloud Config).
Externalize configuration from code.
Supports dynamic updates.
8. What is containerization?
Packaging applications with dependencies using containers (e.g., Docker).
Ensures consistency across environments.
Simplifies deployment and scaling.
9. How to secure microservices?
Use OAuth2, JWT, or API keys for authentication.
Implement security at API Gateway and service level.
Encrypt sensitive data.
10. What is eventual consistency?
Data may not be instantly consistent across services.
Updates propagate over time.
Used in distributed systems for scalability.