Java Interview Preparation
Java Technical Interview Questions
Prepare for Java Core interview questions covering the JVM, language fundamentals, memory, collections, and modern Java features.
Java Core Interview Focus
Prepare for Java Core interview questions covering the JVM, language fundamentals, memory, collections, and modern Java features.
Interview questions
1. What is the difference between JDK, JRE, and JVM? Beginner
The JDK develops Java applications, the JRE runs them, and the JVM executes bytecode. The JDK includes development tools such as javac and the JRE. The JRE contains the JVM and runtime libraries. The JVM loads, verifies, and executes Java bytecode while providing portability across operating systems.
2. What is the difference between HashMap and ConcurrentHashMap? Intermediate
HashMap is not thread-safe and permits one null key. ConcurrentHashMap supports concurrent access using fine-grained coordination, does not allow null keys or values, and provides atomic operations such as putIfAbsent.
Map<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge("java", 1, Integer::sum);3. How does garbage collection work in Java? Intermediate
The garbage collector identifies objects that are no longer reachable from GC roots and reclaims their memory. Modern collectors use generations because most objects become unreachable soon after creation.
4. What is the difference between an interface and an abstract class? Beginner
An interface defines a contract that multiple unrelated classes can implement. An abstract class provides a shared base with state and implementation. Choose an interface for capabilities and an abstract class for a close family of types.
5. What important features were introduced in Java 17? Advanced
Java 17 introduced or finalized features including sealed classes, records, pattern matching for instanceof, text blocks, and a modern LTS release baseline.
public record User(long id, String name) {}
public sealed interface Result permits Success, Failure {}6. What is Object-Oriented Programming? Beginner
Object-Oriented Programming organizes software around classes and objects. Objects combine state, represented by fields, with behavior, represented by methods.
class Car {
String brand;
void start() { System.out.println("Car started"); }
}7. What are the four main principles of OOP? Beginner
The four principles are encapsulation, inheritance, polymorphism, and abstraction. Together they help Java applications remain reusable, maintainable, secure, and extensible.
8. What is a class in Java? Beginner
A class is a blueprint used to create objects. It defines the fields and methods that instances of the class can contain.
class Employee {
int employeeId;
String employeeName;
void work() { }
}9. What is an object in Java? Beginner
An object is an instance of a class. It is created at runtime and contains actual values for the state defined by its class.
Employee employee = new Employee();10. What is the difference between a class and an object? Beginner
A class is a logical blueprint that defines fields and methods. An object is a real runtime instance containing actual values.
11. What is encapsulation in Java? Beginner
Encapsulation wraps data and behavior inside a class and controls access to the data. Private fields with public behavior methods are a common implementation.
class BankAccount {
private double balance;
public void deposit(double amount) { if (amount > 0) balance += amount; }
public double getBalance() { return balance; }
}12. Why should fields normally be private? Beginner
Private fields prevent uncontrolled modification. Methods can validate input and preserve the class invariants before changing internal state.
private double balance;
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException();
balance += amount;
}13. What is inheritance in Java? Beginner
Inheritance allows a child class to reuse and extend the fields and methods of a parent class using the extends keyword.
class Vehicle { void start() {} }
class Car extends Vehicle { void drive() {} }14. What are the benefits of inheritance? Beginner
Inheritance reduces duplicate code, provides a natural relationship between related types, enables extension, and supports runtime polymorphism. It should be used only for a genuine is-a relationship.
15. What types of inheritance does Java support? Beginner
Java supports single, multilevel, and hierarchical inheritance through classes. Multiple inheritance of classes is not supported, but a class can implement multiple interfaces.
16. Why does Java not support multiple inheritance through classes? Intermediate
Multiple class inheritance can create ambiguity when parent classes define the same method, known as the diamond problem. Java avoids this by allowing one direct superclass and multiple interfaces.
17. What is polymorphism in Java? Beginner
Polymorphism means one contract or method name can represent different behavior. Java provides compile-time polymorphism through overloading and runtime polymorphism through overriding.
18. What is compile-time polymorphism? Beginner
Compile-time polymorphism is method overloading. The compiler selects the method using the number, types, and order of the arguments.
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}19. What is runtime polymorphism? Intermediate
Runtime polymorphism is method overriding. A parent reference can point to a child object, and Java selects the child implementation at runtime.
Payment payment = new CreditCardPayment();
payment.processPayment();20. What is method overloading? Beginner
Overloading defines methods with the same name but different parameter lists. Changing only the return type is not valid overloading.
void print(String value) {}
void print(int value) {}21. What is method overriding? Intermediate
Overriding occurs when a child class provides a compatible implementation of an inherited parent method. The child method must respect Java access and return-type rules.
class EmailNotification extends Notification {
@Override void send() { System.out.println("Email"); }
}22. What is the difference between overloading and overriding? Beginner
Overloading uses different parameters and is resolved at compile time. Overriding requires inheritance, the same parameters, and is resolved at runtime.
23. What is abstraction in Java? Beginner
Abstraction hides implementation details and exposes only the operations a caller needs. Java uses abstract classes and interfaces to model abstractions.
24. What is an abstract class? Beginner
An abstract class cannot be instantiated directly. It can contain fields, constructors, concrete methods, and abstract methods that subclasses must implement.
abstract class Employee {
abstract double calculateSalary();
void displayName() {}
}25. What is an interface in Java? Beginner
An interface defines a contract. Classes implement it and can implement multiple interfaces, which provides flexible abstraction without multiple class inheritance.
interface PaymentService {
void processPayment(double amount);
}26. What is the difference between an abstract class and an interface? Intermediate
An abstract class can share state, constructors, and implementation with closely related classes. An interface defines a contract that unrelated classes can implement, and a class can implement multiple interfaces.
27. Can an abstract class have a constructor? Beginner
Yes. Its constructor runs as part of creating a child object and initializes the parent portion of that object.
abstract class Animal {
Animal() { System.out.println("Animal constructor"); }
}28. Can an interface have methods with implementation? Intermediate
Yes. Modern Java interfaces can contain default, static, and private methods in addition to abstract methods.
interface Logger {
default void log(String message) { System.out.println(message); }
}29. What is the this keyword in Java? Beginner
this refers to the current object. It distinguishes fields from parameters, calls current-class methods or constructors, and can pass the current object to another method.
Student(String name) { this.name = name; }30. What is the super keyword in Java? Beginner
super refers to the immediate parent class. It accesses parent members and calls a parent constructor, which must be the first constructor statement.
class Car extends Vehicle {
Car() { super("Car"); }
}31. What is association in Java? Beginner
Association is a relationship between independent objects, such as a teacher teaching students. Both objects can exist independently.
32. What is aggregation? Intermediate
Aggregation is a weak has-a relationship. The contained object is created outside the container and can continue to exist independently.
class Department {
private final List<Employee> employees;
Department(List<Employee> employees) { this.employees = employees; }
}33. What is composition? Intermediate
Composition is a strong has-a relationship where the container owns the lifecycle of the contained object.
class House {
private final List<Room> rooms = List.of(new Room("Bedroom"));
}34. What is the difference between aggregation and composition? Intermediate
Aggregation allows child objects to exist independently and does not fully control their lifecycle. Composition makes the parent responsible for creating and owning the child objects.
35. What is an is-a relationship? Beginner
An is-a relationship represents inheritance. For example, Dog extends Animal means a Dog is an Animal.
class Dog extends Animal { }36. What is a has-a relationship? Beginner
A has-a relationship represents association, aggregation, or composition. For example, a Car has an Engine when Engine is a field of Car.
class Car {
private final Engine engine = new Engine();
}37. What is constructor overloading? Beginner
Constructor overloading provides multiple ways to create an object by defining constructors with different parameter lists.
Product() {}
Product(int id, String name) {}38. Can constructors be overridden? Beginner
No. Constructors are not inherited and belong to their own class. A child constructor can call a parent constructor using super().
39. What is dynamic method dispatch? Intermediate
Dynamic method dispatch is Java’s runtime mechanism for selecting an overridden method based on the actual object rather than the reference type.
Animal animal = new Dog();
animal.makeSound();40. What is upcasting? Beginner
Upcasting assigns a child object to a parent reference. It is safe, automatic, and commonly used for runtime polymorphism.
Animal animal = new Dog();41. What is downcasting? Intermediate
Downcasting converts a parent reference back to a child reference. It must be checked carefully because an incompatible object causes ClassCastException.
if (animal instanceof Dog dog) { dog.makeSound(); }42. Can static methods be overridden? Intermediate
No. Static methods belong to the class. A child declaration with the same signature hides the parent method; the selected method depends on the reference type.
43. Can private methods be overridden? Beginner
No. Private methods are accessible only inside their declaring class and are not inherited. A same-named child method is independent.
44. Can final methods be overridden? Beginner
No. A final method cannot be changed by a subclass. Use final when the implementation must remain fixed.
45. What is a final class? Beginner
A final class cannot be extended. Java’s String class is a common example.
final class SecurityUtil { }46. What is loose coupling? Intermediate
Loose coupling means depending on abstractions rather than concrete implementations. It improves testing, maintenance, extension, and replacement of dependencies.
class OrderService {
private final NotificationService notifications;
OrderService(NotificationService notifications) { this.notifications = notifications; }
}47. What is cohesion? Intermediate
Cohesion describes how closely related a class’s responsibilities are. High cohesion means the class has one focused purpose and is easier to test and maintain.
48. What is an immutable class? Intermediate
An immutable object cannot change after creation. Use final fields, constructor initialization, no setters, defensive copies, and no exposed mutable state.
public final class Employee {
private final int id;
private final String name;
public Employee(int id, String name) { this.id = id; this.name = name; }
}49. Why is composition often preferred over inheritance? Intermediate
Composition avoids unnecessary parent-child coupling and allows implementations to be replaced or tested independently. Use inheritance only when the child truly is a parent type.
50. How is OOP used in Spring Boot applications? Intermediate
Spring Boot uses encapsulated entities and DTOs, service interfaces for abstraction, base types for selective inheritance, polymorphic implementations, and composition through dependency injection.
51. How would you design a payment system using OOP? Advanced
Define a PaymentStrategy interface, implement credit-card, UPI, and wallet strategies, and inject the selected strategy into a PaymentProcessor. This demonstrates abstraction, polymorphism, composition, and loose coupling.
interface PaymentStrategy { void pay(double amount); }
class PaymentProcessor {
private final PaymentStrategy strategy;
PaymentProcessor(PaymentStrategy strategy) { this.strategy = strategy; }
}52. How would you add a new payment type without modifying existing code? Advanced
Create a new class that implements the existing payment interface. The processor remains unchanged, following the Open/Closed Principle.
class WalletPayment implements PaymentStrategy {
public void pay(double amount) { }
}53. Is Java a completely object-oriented language? Beginner
No. Java supports primitive types such as int, double, char, and boolean, which are not objects. Wrapper classes provide object representations when needed.
54. Can we create an object without using new? Intermediate
Yes. Objects can be obtained through factory methods, reflection, cloning, deserialization, or dependency injection. For example, LocalDate.now() returns an object without application code calling new.
LocalDate date = LocalDate.now();55. Can an abstract class be final? Beginner
No. Abstract means the class is designed to be extended, while final prevents extension. Using both creates a contradiction and does not compile.
56. Can a constructor be private? Beginner
Yes. Private constructors prevent direct creation and are useful for utility classes, singleton implementations, and factory-controlled creation.
class ApplicationConfig {
private ApplicationConfig() { }
}57. Can we override an overloaded method? Intermediate
Yes. Overloading and overriding are separate. A child can override one overloaded method while inheriting the other overloads.
58. What are the four pillars of OOP? Beginner
The four pillars are encapsulation, inheritance, polymorphism, and abstraction.
59. What is the difference between an interface and an abstract class? Beginner
An interface defines a contract that multiple classes can implement. An abstract class provides shared state or implementation for a closely related class hierarchy.
60. What is the role of private fields and public methods in OOP? Beginner
Private fields protect internal state while public methods expose controlled behavior. This combination supports encapsulation, validation, and maintainability.
61. What is the relationship between loose coupling and dependency injection? Intermediate
Dependency injection supplies abstractions from outside a class, so the class does not construct concrete dependencies. This is a practical way to achieve loose coupling.
62. What is the difference between state and behavior in an object? Beginner
State is the data held by an object, such as an employee name. Behavior is the work the object performs through methods, such as calculating salary.
63. What is the Open/Closed Principle? Intermediate
Software entities should be open for extension but closed for modification. Interfaces and polymorphic implementations allow new behavior without changing stable client code.
64. What is high cohesion and why is it important? Intermediate
High cohesion keeps closely related responsibilities together and unrelated responsibilities separate. It produces focused classes that are easier to understand, test, and change.
65. What are common OOP best practices in Java? Advanced
Keep fields private, expose behavior instead of mutable state, prefer constructor injection, program to interfaces, favor composition, keep classes focused, use immutable objects, and avoid deep inheritance hierarchies.
66. What is an exception in Java? Beginner
An exception is an unexpected event that interrupts normal program flow. Java creates an exception object containing its type, message, location, and call sequence.
int result = 10 / 0; // ArithmeticException67. What is exception handling? Beginner
Exception handling detects runtime problems and responds gracefully using try, catch, finally, throw, and throws.
68. Why is exception handling important? Beginner
It prevents sudden termination, provides useful messages, separates error handling from business logic, releases resources, and supports logging and monitoring.
69. What is the exception hierarchy in Java? Intermediate
Throwable is the root of Error and Exception. RuntimeException represents unchecked exceptions, while IOException, SQLException, and ClassNotFoundException are common checked exceptions.
Object -> Throwable -> Error
-> Exception -> RuntimeException70. What is the difference between an exception and an error? Beginner
Exceptions are usually application-level problems that may be recoverable. Errors normally indicate serious JVM or system failures such as OutOfMemoryError and should rarely be handled.
71. What are checked exceptions? Beginner
Checked exceptions are verified by the compiler. The caller must handle them with try-catch or declare them with throws. IOException and SQLException are examples.
72. What are unchecked exceptions? Beginner
Unchecked exceptions extend RuntimeException and are not enforced by the compiler. They commonly represent invalid input, programming errors, or invalid state.
73. What is the difference between checked and unchecked exceptions? Beginner
Checked exceptions must be handled or declared and often represent external failures. Unchecked exceptions occur at runtime and commonly represent invalid code, input, or state.
74. What is a try block? Beginner
A try block contains code that may throw an exception and must be followed by catch, finally, or both.
try { int result = 100 / 0; } finally { cleanup(); }75. What is a catch block? Beginner
A catch block handles an exception thrown by its associated try block and can inspect methods such as getMessage, getCause, and printStackTrace.
76. What is a finally block? Beginner
finally contains cleanup code that normally runs whether the try succeeds or an exception is caught. Try-with-resources is preferred for closeable resources.
77. Is the finally block always executed? Intermediate
It normally executes, but not after System.exit, an unexpected JVM or operating-system termination, or a fatal process failure.
78. Can we use try without catch? Beginner
Yes. A try block may be followed by finally without catch. The exception is still propagated after cleanup.
try { process(); } finally { release(); }79. Can we use catch without try? Beginner
No. Every catch block must be associated with a try block, otherwise the code does not compile.
80. Can we use multiple catch blocks? Beginner
Yes. Multiple catch blocks allow different exception types to receive different recovery messages or actions.
try { process(); } catch (NumberFormatException e) { } catch (ArithmeticException e) { }81. What is the correct order of multiple catch blocks? Intermediate
Specific exception types must appear before general types. A catch(Exception) before catch(IOException) makes the latter unreachable.
82. What is multi-catch in Java? Beginner
Multi-catch handles unrelated exception types in one catch block when their handling logic is identical. It was introduced in Java 7.
catch (NumberFormatException | ArithmeticException exception) {
log.warn("Invalid number", exception);
}83. Can related exceptions be used in the same multi-catch? Intermediate
No. Multi-catch alternatives cannot have a parent-child relationship, such as IOException and FileNotFoundException. Use the parent type instead.
84. What is the throw keyword? Beginner
throw explicitly creates and raises one exception object, usually when input or a business rule is invalid.
if (age < 18) throw new IllegalArgumentException("Age must be at least 18");85. What is the throws keyword? Beginner
throws declares checked exceptions that a method may pass to its caller. The caller must handle or further declare them.
String readFile(String path) throws IOException { return Files.readString(Path.of(path)); }86. What is the difference between throw and throws? Beginner
throw raises an exception object inside code. throws declares exception types in a method signature and can list multiple types.
87. What is exception propagation? Intermediate
Exception propagation passes an unhandled exception up the method-call stack until a compatible handler is found or the JVM default handler terminates the thread.
88. Do checked and unchecked exceptions both propagate? Intermediate
Yes. Both can move through method calls. Checked exceptions must be handled or declared at required boundaries, while unchecked exceptions do not require declaration.
89. What is a custom exception? Beginner
A custom exception is a domain-specific exception created to express a business or application failure clearly.
class InsufficientBalanceException extends RuntimeException {
InsufficientBalanceException(String message) { super(message); }
}90. How do you create a checked custom exception? Beginner
Extend Exception and declare or handle it at the call site.
class InvalidFileFormatException extends Exception {
InvalidFileFormatException(String message) { super(message); }
}91. How do you create an unchecked custom exception? Beginner
Extend RuntimeException. The compiler does not force callers to handle or declare it.
class EmployeeNotFoundException extends RuntimeException { }92. When should checked exceptions be used? Intermediate
Use them when a caller can reasonably recover from an external condition such as a missing file, failed network connection, or unavailable resource.
93. When should unchecked exceptions be used? Intermediate
Use them for invalid arguments, violated business rules, missing entities, invalid application state, or failures that the current layer cannot meaningfully recover from.
94. What is try-with-resources? Beginner
Try-with-resources automatically closes resources implementing AutoCloseable or Closeable after the try block completes.
try (BufferedReader reader = Files.newBufferedReader(path)) {
return reader.readLine();
}95. What are the benefits of try-with-resources? Beginner
It reduces boilerplate, prevents resource leaks, closes resources reliably, and handles cleanup exceptions more safely than manual finally code.
96. Can multiple resources be declared in try-with-resources? Beginner
Yes. Resources are closed automatically in reverse order of declaration.
try (Reader reader = openReader(); Writer writer = openWriter()) { copy(reader, writer); }97. What is the AutoCloseable interface? Beginner
AutoCloseable marks a resource that can be closed automatically. Its close method may throw Exception and is invoked by try-with-resources.
class DatabaseSession implements AutoCloseable {
public void close() { }
}98. What is a suppressed exception? Advanced
If the try body throws and close also throws, the body exception is primary and the close exception is attached as suppressed through getSuppressed().
99. What happens when try and finally both return? Advanced
The return from finally overrides the return from try. Returning from finally is bad practice because it can hide exceptions and results.
static int value() { try { return 10; } finally { return 20; } }100. What happens when finally throws an exception? Advanced
An exception from finally can hide an exception from try or catch. Cleanup code should avoid throwing unless there is no safe alternative.
101. What is exception chaining? Intermediate
Exception chaining wraps a low-level exception in a higher-level exception while preserving the original cause for debugging.
throw new DataAccessException("Unable to load data", sqlException);102. Why should the original exception cause be preserved? Intermediate
The cause preserves the original stack trace, root-cause details, and debugging context needed for production diagnosis.
throw new RuntimeException("Database failed", exception);103. What is a stack trace? Beginner
A stack trace shows the exception type and the sequence of method calls, classes, files, and line numbers that led to the failure.
104. What is the difference between getMessage and printStackTrace? Beginner
getMessage returns only the exception message. printStackTrace prints the complete call sequence and should normally be replaced by a logging framework in production.
105. Why should printStackTrace be avoided in production? Intermediate
It writes unstructured output directly to standard error, may bypass centralized logging, cannot be controlled by log level, and may expose sensitive details.
106. What is the difference between final, finally, and finalize? Beginner
final prevents reassignment, overriding, or inheritance. finally provides cleanup flow. finalize is a deprecated cleanup callback and must not be used for resources.
107. Can we catch Throwable? Advanced
Technically yes, but it also catches serious Errors such as OutOfMemoryError and StackOverflowError. Catch specific exceptions instead.
108. Can we catch Error? Advanced
Technically yes, but catching Error does not guarantee safe recovery. Most Errors represent severe JVM or system failures.
109. Why is catching Exception everywhere bad practice? Intermediate
It handles unrelated failures together, hides programming errors, weakens recovery decisions, and makes debugging harder. Catch specific types instead.
110. What is exception swallowing? Beginner
Exception swallowing is catching an exception without logging, handling, or rethrowing it. It makes failures invisible and should be avoided.
catch (PaymentException exception) {
log.error("Payment failed", exception);
throw exception;
}111. Should exceptions be used for normal program flow? Intermediate
No. Validate predictable conditions normally and use exceptions for exceptional failures. Frequent exceptions create unnecessary stack traces and obscure intent.
112. Can an overriding method throw a checked exception? Advanced
It can throw the same checked exception, a narrower subclass, or none. It cannot throw a broader checked exception than the parent method.
113. Can an overriding method throw an unchecked exception? Intermediate
Yes. Unchecked exceptions are not restricted by the checked-exception overriding rules.
114. Can a constructor throw an exception? Beginner
Yes. A constructor can throw checked or unchecked exceptions. If it fails, the object is not created successfully.
Employee(String name) {
if (name == null) throw new IllegalArgumentException();
}115. Can a static initialization block throw an exception? Advanced
It can throw unchecked exceptions. A failure during class initialization may be reported as ExceptionInInitializerError.
116. How are exceptions handled in Spring Boot? Intermediate
They can be handled locally, with @ExceptionHandler, globally with @RestControllerAdvice, or translated into custom structured API errors. Centralized handling is preferred for REST APIs.
117. What is @ExceptionHandler in Spring Boot? Beginner
@ExceptionHandler maps a specified exception to a handler method in a controller or controller advice class.
@ExceptionHandler(EmployeeNotFoundException.class)
ResponseEntity<ApiError> handle(EmployeeNotFoundException ex) { return ResponseEntity.notFound().build(); }118. What is @ControllerAdvice? Beginner
@ControllerAdvice centralizes shared controller behavior, including exception handlers, across multiple controllers.
119. What is @RestControllerAdvice? Beginner
@RestControllerAdvice combines controller advice with response-body behavior and is commonly used for global REST API exception handling.
120. How do you create a standard API error response? Intermediate
Use a consistent object containing timestamp, status, safe error code, message, path, correlation ID, and validation field errors.
public record ApiError(Instant timestamp, int status, String errorCode, String message, String path) {}121. How should a not-found exception be handled in Spring Boot? Beginner
Throw a custom EmployeeNotFoundException from the service, handle it in global advice, and return a safe 404 response with a stable error code.
122. How are validation exceptions handled in Spring Boot? Intermediate
Handle MethodArgumentNotValidException in global advice, collect field errors, and return a structured 400 or 422 response.
123. What is the difference between business and system exceptions? Intermediate
Business exceptions represent known rule violations and usually map to 4xx responses. System exceptions represent technical failures and usually map to 5xx responses.
124. Should controllers contain large try-catch blocks? Beginner
Generally no. Keep controllers focused on HTTP mapping and let global advice translate service and domain exceptions consistently.
125. What HTTP status codes are commonly used for exceptions? Beginner
400 represents invalid input, 401 authentication, 403 access denial, 404 missing resources, 409 conflicts, 429 rate limits, 500 unexpected errors, and 503 unavailable dependencies.
126. How should exceptions be handled between microservices? Intermediate
Return safe structured errors with status, business code, message, timestamp, path, and correlation ID. Keep stack traces and internal details in secured server logs.
127. How do you handle downstream service failures? Advanced
Configure timeouts, classify client errors, retry only transient failures, use circuit breakers, preserve causes, log trace IDs, and avoid exposing downstream internals.
128. Should every exception be retried? Advanced
No. Retry transient timeouts or temporary unavailability with bounded exponential backoff. Do not retry validation, authentication, not-found, or non-idempotent failures without protection.
129. What is the role of a correlation ID? Intermediate
A correlation ID connects logs for one request across gateways, services, databases, Kafka, and downstream calls, making distributed failures traceable.
130. How should Kafka consumer exceptions be handled? Advanced
Classify transient and permanent failures, use bounded retry with backoff, dead-letter topics, idempotent processing, acknowledgements, and monitoring for retry and dead-letter counts.
131. What is a dead-letter topic? Intermediate
A dead-letter topic stores messages that still fail after configured retries so the main consumer can continue and operators can investigate or replay them.
132. What is a poison-pill message? Intermediate
A poison-pill message repeatedly fails because of invalid data, schema, or deserialization. It should be isolated after bounded retries instead of blocking the consumer forever.
133. How should database exceptions be handled? Advanced
Translate persistence failures into meaningful application exceptions, log safe context, propagate to global handling, and never expose SQL, credentials, schema details, or vendor messages.
134. What is exception translation in Spring? Advanced
Spring translates vendor-specific database failures into a consistent DataAccessException hierarchy, such as DuplicateKeyException and DataIntegrityViolationException.
135. How do exceptions affect Spring transactions? Advanced
By default, Spring rolls back for RuntimeException and Error but not for checked exceptions.
@Transactional
public void createOrder(Order order) {
repository.save(order);
throw new IllegalStateException("Failed");
}136. How do you roll back a Spring transaction for a checked exception? Advanced
Use @Transactional(rollbackFor = IOException.class) or another explicitly configured exception type.
@Transactional(rollbackFor = IOException.class)
public void importOrders() throws IOException { }137. What happens when an exception is caught inside a transactional method? Advanced
If a runtime exception is caught and swallowed, Spring may commit the transaction. Rethrow it or explicitly mark rollback when failure should undo the work.
138. How would you handle an employee-not-found scenario? Beginner
Throw a custom unchecked exception in the service, map it globally, and return a safe 404 Not Found response.
139. How would you handle a duplicate employee email? Advanced
Enforce a database unique constraint, translate DataIntegrityViolationException, and return 409 Conflict. A pre-check alone is unsafe under concurrency.
140. How would you handle an external API timeout? Advanced
Configure timeouts, retry safely with backoff, use a circuit breaker, preserve the cause, log correlation details, and return a safe service-unavailable response.
141. How would you handle exceptions in a scheduled job? Intermediate
Catch failures at the job boundary, log job and execution IDs, record metrics, isolate item failures when appropriate, retry transient work, and notify support for critical failures.
142. How would you handle an exception in asynchronous code? Advanced
Observe CompletableFuture or reactive failures with exceptionally, handle, or an equivalent error path. Do not allow asynchronous failures to disappear silently.
CompletableFuture.supplyAsync(service::load).exceptionally(error -> { log.error("Async failed", error); return List.of(); });143. How would you design exception handling for a layered application? Advanced
Repositories handle persistence details, services enforce business rules, controllers remain thin, global advice maps errors to responses, and logging/monitoring captures technical context.
144. What happens if no matching catch block is found? Beginner
The exception propagates to the caller. If nobody handles it, the JVM default handler prints details and terminates the affected thread.
145. What happens if an exception occurs inside a catch block? Intermediate
The new exception propagates unless another surrounding try-catch handles it. The original handler does not automatically handle failures created inside itself.
146. Can one exception handler handle multiple exception types? Beginner
Yes, multi-catch can handle unrelated exception types in one block when their handling logic is the same.
147. Can we rethrow an exception? Beginner
Yes. A handler can log and rethrow the same exception or wrap it in a higher-level exception while preserving the cause.
catch (PaymentException ex) { log.error("Payment failed", ex); throw ex; }148. Can a method declare an unchecked exception using throws? Beginner
Yes, but it is optional because the compiler does not require unchecked exceptions to be declared. It may still document the method contract.
149. Can the main method throw an exception? Beginner
Yes. An unhandled exception declared by main reaches the JVM default handler and normally terminates the application.
public static void main(String[] args) throws IOException { }150. Can we have nested try-catch blocks? Beginner
Yes, but excessive nesting makes control flow hard to understand. Prefer focused methods and specific handlers.
151. What are best practices for exception handling? Advanced
Catch specific exceptions, avoid empty catches, preserve causes, use custom domain errors, prefer try-with-resources, avoid finally returns, log safely, centralize REST handling, and distinguish retryable failures.
152. Should we log and rethrow the same exception? Intermediate
Usually not at every layer. Add context when wrapping and log once at the boundary that has enough business and technical context.
153. What information should be included in exception logs? Advanced
Include exception and stack trace, correlation and trace IDs, operation, safe business identifiers, downstream service, retry count, and duration. Never log credentials, tokens, or unmasked sensitive data.
154. What should not be returned to API clients? Beginner
Do not return stack traces, SQL, class names, file paths, internal addresses, credentials, tokens, or raw downstream errors. Return a safe structured error instead.
How to Prepare for Java Technical Interviews
Use this Java technical interview question bank to revise core concepts and practise explaining your decisions clearly. The questions cover Java fundamentals, object-oriented programming, collections, exceptions, multithreading, Spring Boot, Hibernate, databases, and other topics used in real software development interviews.
Start with the fundamentals, then move to scenario-based questions and advanced topics. Filter questions by difficulty to build confidence gradually. A strong answer should define the concept, explain why it matters, and include a practical example when appropriate.
Continue your preparation with the Java tutorials, or explore all interview preparation tracks for managerial and company-focused questions.
