Skip to content

Java Interview Questions for 3 Years Experience

40 questions with answers for candidates with 3 years of experience — 5 easy, 28 medium, 7 hard.

What interviewers expect: 3 years experience

Three year candidates are judged as independent backend engineers. Expect strong questions on concurrency, CompletableFuture, Spring internals like proxies and auto-configuration, microservice communication and caching. You should discuss performance improvements you made with numbers, and handle medium to hard DSA plus low level design with design patterns. Clear answers on testing strategy also help.

This set is weighted towards Spring Boot and Microservices (7), Java 8+ Features and Streams (6), OOP in Java (6), JDBC, Hibernate and JPA (6).

Concurrency and CompletableFuture Spring internals Microservices and Kafka Design patterns and LLD
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is Spring Boot Actuator used for?

Save to ▾
Show answer
Actuator adds production endpoints such as /actuator/health for liveness and readiness probes, /actuator/metrics and /actuator/prometheus for Micrometer metrics, plus info, loggers and thread dumps. Expose only what you need with management.endpoints.web.exposure.include and secure sensitive endpoints with Spring Security. Kubernetes uses the health groups to decide restarts and traffic routing.
02

What is the difference between synchronized and ReentrantLock?

Save to ▾
Show answer
synchronized is a built-in keyword that locks a monitor and releases it automatically at block exit. ReentrantLock is an explicit lock that adds tryLock with timeout, interruptible locking, fairness options and multiple Condition objects, but you must unlock in a finally block. Both are reentrant. Prefer synchronized for simple cases and ReentrantLock when you need its extra features.
03

Run two tasks in parallel with CompletableFuture and combine their results.

Save to ▾
Show answer
Use a dedicated executor for I/O work. ExecutorService pool = Executors.newFixedThreadPool(4); CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userApi.get(id), pool); CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> orderApi.list(id), pool); Profile p = user.thenCombine(orders, Profile::new) .orTimeout(2, TimeUnit.SECONDS) .join();
04

An API calls three independent downstream services one after another and takes 900 ms. How would you speed it up?

Save to ▾
Show answer
Since the calls are independent, run them in parallel with CompletableFuture.supplyAsync on a dedicated executor or with virtual threads, then join with allOf. Total latency becomes roughly the slowest call, about 300 ms. Add a timeout per call with orTimeout and a fallback for failures so one slow service does not block the whole response. Structured concurrency is another option in newer Java.
05

A @Transactional method is not rolling back after an exception. What could be wrong?

Save to ▾
Show answer
Check that the exception is unchecked, since checked exceptions do not roll back unless rollbackFor is set. Check that the method is called through the Spring proxy, not from another method in the same class. Make sure the method is public and the exception is not caught and swallowed inside. Also confirm the database engine supports transactions and the right transaction manager is used.
06

Using streams, find the employee with the highest salary in each department.

Save to ▾
Show answer
Group by department with a maxBy downstream collector. Map<String, Optional<Employee>> top = employees.stream() .collect(Collectors.groupingBy( Employee::department, Collectors.maxBy(Comparator.comparingInt(Employee::salary)))); To get values without Optional, wrap with collectingAndThen(maxBy(...), Optional::get), which is safe because each group has at least one element.
07

Write a custom unchecked exception and a Spring handler that returns HTTP 404.

Save to ▾
Show answer
Define the exception, then map it centrally. public class NotFoundException extends RuntimeException { public NotFoundException(String msg) { super(msg); } } @RestControllerAdvice public class ApiErrors { @ExceptionHandler(NotFoundException.class) public ProblemDetail notFound(NotFoundException e) { return ProblemDetail.forStatusAndDetail( HttpStatus.NOT_FOUND, e.getMessage()); } }
08

Why should we hire you as a Java backend developer?

Save to ▾
Show answer
Situation: in my current role I build Spring Boot services for a payments product. Task: show impact beyond writing code. Action: I improved API latency by 60 percent through query tuning and caching, raised test coverage from 40 to 80 percent and handled on-call calmly. Result: I bring solid Java, Spring and SQL skills, ownership of production and a habit of measuring results, which fits this role.
09

Which JVM flags would you set to start a production service with a 4 GB heap, G1 and a heap dump on OOM?

Save to ▾
Show answer
A typical command is: java -Xms4g -Xmx4g \ -XX:+UseG1GC -XX:MaxGCPauseMillis=200 \ -XX:+HeapDumpOnOutOfMemoryError \ -XX:HeapDumpPath=/var/log/app \ -Xlog:gc*:file=/var/log/app/gc.log \ -jar app.jar In containers prefer -XX:MaxRAMPercentage=75 so the heap follows the container memory limit.
10

What is the difference between List.of(), Arrays.asList() and Collections.unmodifiableList()?

Save to ▾
Show answer
List.of() returns a truly immutable list; add, set and remove throw exceptions and nulls are not allowed. Arrays.asList() returns a fixed-size list backed by the array: set() works and writes through to the array, but add() and remove() throw. Collections.unmodifiableList() is a read-only view, so changes to the original list are still visible through it.
11

Tell me about a time you found and fixed a difficult production bug in a Java application.

Save to ▾
Show answer
Situation: our order service crashed with OutOfMemoryError every few days. Task: find the root cause without long downtime. Action: I enabled heap dumps on OOM, analysed the dump in Eclipse MAT and found a static HashMap used as a cache that was never cleared. I replaced it with a bounded Caffeine cache with expiry and added a heap usage alert. Result: no crashes in six months and memory stayed flat.
12

You need to add a new payment method to a system that has a big if-else on payment type. How would you redesign it?

Save to ▾
Show answer
This breaks the Open/Closed principle. I would create a PaymentProcessor interface with a pay() method and one implementation per type, such as UpiProcessor and CardProcessor. A factory or a Spring map of beans keyed by type picks the right one. Adding a new method then means adding one new class without touching existing tested code, and each processor can be unit tested alone.
13

What is the role of the JIT compiler?

Save to ▾
Show answer
The JVM first interprets bytecode, then profiles which methods run often. The Just In Time compiler converts these hot methods into optimised native code at runtime. HotSpot uses tiered compilation: C1 compiles quickly with light optimisation and C2 applies aggressive optimisations like inlining and escape analysis. This is why Java apps get faster after a warm-up period.
14

Explain the entity lifecycle states in JPA.

Save to ▾
Show answer
Transient: a new object not yet linked to a persistence context. Managed (persistent): attached to the context, so changes are tracked and flushed automatically through dirty checking. Detached: was managed but the context closed or it was evicted; changes are not tracked until merge(). Removed: scheduled for deletion on flush. persist, merge, detach and remove move entities between these states.
15

Explain pattern matching for switch and record patterns in Java 21.

Save to ▾
Show answer
Pattern matching for switch lets a case match on type and bind a variable, such as case Circle c -> Math.PI * c.r() * c.r(). Record patterns deconstruct a record directly: case Point(int x, int y). Guards add conditions with when. With sealed types the compiler checks the switch is exhaustive, so adding a new subtype causes a compile error where it is not handled.
16

Write a Kafka producer and consumer in Spring Boot.

Save to ▾
Show answer
Spring Kafka hides most boilerplate. @Service class OrderEvents { private final KafkaTemplate<String, OrderPlaced> kafka; OrderEvents(KafkaTemplate<String, OrderPlaced> k) { kafka = k; } void publish(OrderPlaced e) { kafka.send("orders", e.orderId(), e); } } @Component class OrderListener { @KafkaListener(topics = "orders", groupId = "inventory") void on(OrderPlaced e) { inventory.reserve(e); } } Using orderId as key keeps events for one order in the same partition and order.
17

toMap() throws Duplicate key exception in production. How do you fix it?

Save to ▾
Show answer
The data has repeated keys that the developer assumed were unique. Decide the business rule, then pass a merge function, for example toMap(User::email, u -> u, (a, b) -> a) to keep the first, or use groupingBy if all values are needed. Also check upstream data quality, since duplicates may signal a deeper bug such as missing unique constraints.
18

A file handle leak causes Too many open files errors after a day. What is the likely cause?

Save to ▾
Show answer
Streams, readers or connections are opened but not closed on all paths, especially when an exception is thrown before close(). Check with lsof or jcmd which files are open. Fix by wrapping every resource in try-with-resources so it always closes, and make sure Files.lines() and Files.list() streams are closed too, since they hold file handles.
19

Describe a time you improved the design of existing code.

Save to ▾
Show answer
Situation: our notification module used a 400 line class with switch cases for email, SMS and WhatsApp. Task: add push notifications without breaking anything. Action: I wrote tests for current behaviour, extracted a Notifier interface with one class per channel and used Spring to inject them by type. Result: push was added in one new class, bugs in that module dropped and new channels now take hours, not days.
20

You need to process a 5 GB file using streams without running out of memory. How?

Save to ▾
Show answer
Use Files.lines(path), which reads lazily line by line, inside try-with-resources. Apply filter and map, then aggregate with a collector that keeps small results such as counts or sums instead of collecting all lines into a list. If the output is large, write it incrementally to a BufferedWriter. Avoid sorted() and distinct() on huge data because they buffer everything.
21

What is the difference between JPA, Hibernate and Spring Data JPA?

Save to ▾
Show answer
JPA, now Jakarta Persistence, is a specification of interfaces and annotations for object relational mapping. Hibernate is the most popular implementation of that specification and adds its own features. Spring Data JPA sits on top and generates repository implementations from interfaces and method names like findByEmail, reducing boilerplate. Your code uses JPA annotations, Hibernate does the work and Spring Data simplifies access.
22

Should a service layer throw checked or unchecked exceptions? Defend your choice.

Save to ▾
Show answer
I prefer unchecked domain exceptions in the service layer. Checked exceptions force every caller to catch or declare them, leak low level details through layers and do not work well with lambdas. Unchecked exceptions with clear names, handled centrally by a controller advice, keep code clean. Spring follows the same idea by translating SQLException into its unchecked DataAccessException family.
23

Implement the Builder pattern for a User class with many optional fields.

Save to ▾
Show answer
A builder avoids long constructors. public class User { private final String name; private final int age; private User(Builder b) { name = b.name; age = b.age; } public static class Builder { private String name; private int age; public Builder name(String n) { name = n; return this; } public Builder age(int a) { age = a; return this; } public User build() { return new User(this); } } } Usage: new User.Builder().name("Asha").age(25).build(). Lombok @Builder generates this.
24

What is the difference between static and dynamic binding?

Save to ▾
Show answer
Static binding is resolved at compile time and applies to private, static and final methods and to overloaded methods, because the compiler knows exactly which method to call. Dynamic binding is resolved at runtime based on the actual object type and applies to overridden instance methods. Static methods are hidden, not overridden, so the reference type decides which one runs.
25

What is the difference between ArrayList and LinkedList?

Save to ▾
Show answer
ArrayList is backed by a resizable array, so get(i) is O(1) and appends are amortised O(1), but inserting in the middle shifts elements. LinkedList is a doubly linked list with O(n) random access but O(1) add or remove at the ends or through an iterator. In practice ArrayList is faster for almost all cases because of better CPU cache use; use ArrayDeque for queues.
26

Is it good practice to catch Exception or Throwable?

Save to ▾
Show answer
Usually no. Catching Throwable also catches Errors like OutOfMemoryError that the app cannot recover from, and catching Exception hides bugs by treating all failures the same. Catch the most specific exceptions you can handle. A broad catch is acceptable only at a top boundary, such as a global handler or thread entry point, where you log and return a safe error.
27

What is a ClassLoader and what is the delegation model?

Save to ▾
Show answer
A ClassLoader loads .class files into the JVM. The main loaders are Bootstrap (core classes), Platform (formerly Extension) and Application (classpath). In the parent delegation model a loader first asks its parent to load a class and only loads it itself if the parent cannot. This prevents user code from replacing core classes like java.lang.String.
28

Write a thread safe singleton class in Java.

Save to ▾
Show answer
The simplest safe options are an enum or the holder idiom. public class Config { private Config() {} private static class Holder { static final Config INSTANCE = new Config(); } public static Config getInstance() { return Holder.INSTANCE; } } The JVM loads Holder lazily and class initialisation is thread safe. An enum singleton also resists reflection and serialization attacks.
29

What are the key patterns used in microservices built with Spring Boot?

Save to ▾
Show answer
Common patterns are API gateway (Spring Cloud Gateway) for routing and auth, service discovery or Kubernetes services, externalised config, circuit breaker and retry with Resilience4j, database per service, event-driven communication with Kafka, saga for distributed transactions, and observability with Micrometer, tracing and centralised logs. Each service owns its data and deploys independently.
30

You must expose configuration that differs between dev, QA and production. How do you manage it?

Save to ▾
Show answer
Use Spring profiles with application-dev.yml and application-prod.yml, and bind settings to typed @ConfigurationProperties classes with validation. Keep secrets out of the repo by injecting them through environment variables, Kubernetes Secrets or a vault. Activate the profile with SPRING_PROFILES_ACTIVE in each environment. Use the same build artefact everywhere and change only configuration.
31

What does effectively final mean for lambdas?

Save to ▾
Show answer
A lambda can use a local variable from the enclosing method only if that variable is final or effectively final, meaning it is never reassigned after initialisation. Lambdas capture the value, not the variable, so this avoids confusing behaviour and races. To accumulate results, use a stream collector or an AtomicInteger instead of changing a captured local.
32

Map a one-to-many relation between Order and OrderItem in JPA.

Save to ▾
Show answer
Make the child own the foreign key and keep both sides in sync. @Entity class Order { @Id @GeneratedValue Long id; @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) List<OrderItem> items = new ArrayList<>(); void addItem(OrderItem i) { items.add(i); i.setOrder(this); } } @Entity class OrderItem { @Id @GeneratedValue Long id; @ManyToOne(fetch = FetchType.LAZY) Order order; }
33

An API listing 100 orders fires 101 SQL queries. How do you fix it?

Save to ▾
Show answer
This is the N+1 problem from a lazy association loaded in a loop or by JSON serialisation. Fetch what the endpoint needs in one query with JOIN FETCH or @EntityGraph(attributePaths = "items"), or use a DTO projection query. For collections with pagination, fetch ids first, then fetch associations in a second query to avoid in-memory paging. Add a test that asserts the query count.
34

What is the difference between checked and unchecked exceptions?

Save to ▾
Show answer
Checked exceptions extend Exception (but not RuntimeException) and must be caught or declared with throws, for example IOException and SQLException. Unchecked exceptions extend RuntimeException, such as NullPointerException and IllegalArgumentException, and need no declaration. Use checked exceptions for recoverable conditions callers must handle and unchecked ones for programming errors. Errors like OutOfMemoryError should not be caught.
35

A deep inheritance hierarchy of six levels is hard to change. How would you refactor it?

Save to ▾
Show answer
I would identify which behaviours actually vary and pull them into small interfaces, then replace inheritance with composition where a class holds strategy objects. Shared helper code can move to separate components. I would refactor step by step behind existing tests, starting from the leaves, so behaviour stays the same. The result is flatter classes that are easier to test and extend.
36

Find the second highest salary from a list of employees using streams.

Save to ▾
Show answer
Sort distinct salaries in descending order and skip one. Optional<Integer> second = employees.stream() .map(Employee::salary) .distinct() .sorted(Comparator.reverseOrder()) .skip(1) .findFirst(); This returns empty if fewer than two distinct salaries exist. For huge data a single pass tracking top two is O(n).
37

What does the volatile keyword guarantee?

Save to ▾
Show answer
volatile guarantees visibility and ordering: a write to a volatile field is immediately visible to other threads, and it prevents reordering around that access under the Java Memory Model. It does not make compound operations like count++ atomic, because that is a read, modify and write. Use it for flags such as a stop signal, and use AtomicInteger or locks for counters.
38

How do you make sure database changes are released safely?

Save to ▾
Show answer
Situation: a manual schema change once broke our staging environment. Task: make migrations reliable. Action: I introduced Flyway with versioned scripts in the repo, required backward compatible changes such as adding nullable columns first, and ran migrations in CI against a test database. Result: we had zero failed migrations over the next year and rollbacks became predictable.
39

Write a minimal Dockerfile for a Spring Boot application.

Save to ▾
Show answer
A multi-stage build keeps the image small. FROM eclipse-temurin:21-jdk AS build WORKDIR /app COPY . . RUN ./mvnw -q package -DskipTests FROM eclipse-temurin:21-jre WORKDIR /app COPY --from=build /app/target/*.jar app.jar EXPOSE 8080 ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"] Spring Boot can also build images without a Dockerfile using mvn spring-boot:build-image.
40

What is the difference between lazy and eager loading?

Save to ▾
Show answer
Lazy loading fetches an association only when it is first accessed, using a proxy; eager loading fetches it immediately with the parent. In JPA, @ManyToOne and @OneToOne default to EAGER, while @OneToMany and @ManyToMany default to LAZY. Best practice is to make all associations lazy and fetch what each use case needs with JOIN FETCH or entity graphs, which avoids loading huge object graphs.

Frequently asked questions

What is asked in Java interviews for 3 years of experience?

Three year candidates are judged as independent backend engineers. Expect strong questions on concurrency, CompletableFuture, Spring internals like proxies and auto-configuration, microservice communication and caching. You should discuss performance improvements you made with numbers, and handle medium to hard DSA plus low level design with design patterns. Clear answers on testing strategy also help.

How many questions should I practise before a Java interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for 3 years of experience?

Focus first on Concurrency and CompletableFuture, Spring internals, Microservices and Kafka, Design patterns and LLD.