Java interview questions for 2 years experience
18 min readUpdated
With a couple of years of experience, interviewers expect more than definitions: how things work inside, trade-offs, and examples from your own projects. These questions reflect that level, with code where it makes the answer clearer.
Core Java in depth
1. How does HashMap behave under heavy collisions, and what changed in Java 8?
Colliding keys share a bucket. Before Java 8 a bucket was a linked list, so a worst case was O(n). Since Java 8 a bucket with more than 8 entries (in a table of at least 64 buckets) becomes a red-black tree, so the worst case is O(log n). A good hashCode() still matters most.
2. How do you design an immutable class, and why bother?
final class, private final fields set in the constructor, no setters, defensive copies of mutable inputs and outputs (List.copyOf). Immutable objects are thread safe, safe as map keys and easy to reason about. Records give you most of this in one line.
3. What is the difference between Comparable and Comparator, and how do you sort by several fields?
Comparable is the natural order inside the class; Comparator is an external order. Chain comparators: Comparator.comparing(Employee::dept).thenComparing(Employee::salary, Comparator.reverseOrder()).
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class MultiFieldSort {
record Employee(String name, String dept, int salary) {}
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Ravi", "Sales", 60000),
new Employee("Asha", "Engineering", 90000),
new Employee("Meera", "Sales", 75000),
new Employee("John", "Engineering", 90000)));
staff.sort(Comparator.comparing(Employee::dept)
.thenComparing(Employee::salary, Comparator.reverseOrder())
.thenComparing(Employee::name));
staff.forEach(e -> System.out.println(e.dept() + " " + e.salary() + " " + e.name()));
}
}Output
Engineering 90000 Asha Engineering 90000 John Sales 75000 Meera Sales 60000 Ravi
4. Explain checked versus unchecked exceptions and how you design them in an application.
Checked exceptions force the caller to handle a recoverable situation (a missing file); unchecked ones signal bugs or rule violations. In layered applications most teams throw unchecked domain exceptions (OrderNotFoundException) and translate them to HTTP responses in one place, such as a @RestControllerAdvice.
5. What is the difference between final, finally and finalize()?
final stops reassignment, overriding or extending. finally is the block that always runs after try. finalize() was a cleanup hook called by the garbage collector; it is deprecated, so use try-with-resources or Cleaner instead.
6. What is the string pool, and when does intern() help?
String literals are stored once in a pool in the heap and shared. new String("x") creates a separate object; intern() returns the pooled copy. Interning helps only when you hold millions of repeated strings; for comparison, always use equals().
7. What is type erasure, and what can you not do because of it?
Generic type information is removed after compilation, so at run time a List<String> is just a List. You cannot write new T(), T.class, instanceof List<String> or create a generic array new T[10].
Java 8 and later
8. How do streams differ from loops, and when would you not use a stream?
Streams describe what to compute as a pipeline and are lazy; loops describe how, step by step. Prefer a loop when you need to break early with complex state, modify local variables, or when the stream version is harder to read.
9. What is the difference between map and flatMap, and between Optional.map and Optional.flatMap?
map turns each element into one value; flatMap turns each element into a stream (or an Optional) and flattens the result, so you do not end up with Stream<Stream<T>> or Optional<Optional<T>>.
10. How do you group and count with streams?
Collectors.groupingBy(classifier, Collectors.counting()), or another downstream collector such as averagingInt or mapping. Pass TreeMap::new as the map factory if you need sorted keys.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GroupingDemo {
record Order(String city, int amount) {}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("Pune", 500), new Order("Delhi", 1200),
new Order("Pune", 700), new Order("Chennai", 300),
new Order("Delhi", 800));
Map<String, Long> count = orders.stream()
.collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.counting()));
Map<String, Integer> total = orders.stream()
.collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.summingInt(Order::amount)));
System.out.println(count);
System.out.println(total);
}
}Output
{Chennai=1, Delhi=2, Pune=2}
{Chennai=300, Delhi=2000, Pune=1200}11. When is a parallel stream a bad idea?
When the data is small, the work per element is tiny, the source splits badly (such as a LinkedList), the operations have side effects or need order, or the code runs inside a server that already uses all its threads. Measure before using it.
12. What are records and sealed classes?
A record is an immutable data class with constructor, accessors, equals, hashCode and toString generated. A sealed class or interface lists exactly which classes may extend it, so a switch over it can be checked for completeness.
13. What are virtual threads and when would you use them?
Lightweight threads in Java 21 that are cheap to create and block. They let thread-per-request servers handle many more concurrent I/O-bound requests with simple blocking code. They do not make CPU-bound work faster.
Concurrency
14. How does ConcurrentHashMap stay thread safe without locking everything?
Reads take no lock. Writes use compare-and-set for empty buckets and lock only the first node of a bucket otherwise, so threads updating different keys rarely wait for each other. Use compute, merge and putIfAbsent for atomic updates.
15. How would you run three independent service calls in parallel and combine the results?
Start each with CompletableFuture.supplyAsync(..., executor), combine with thenCombine or allOf(...).thenApply(...), add a timeout with orTimeout and a fallback with exceptionally.
16. What causes a deadlock, and how have you avoided one?
Threads taking the same locks in different orders. Avoid it by ordering locks consistently (for example, always lock the account with the lower id first), keeping locked sections small, and using tryLock with a timeout where needed.
17. What is the Java memory model's happens-before rule?
A set of guarantees about when one thread's writes are visible to another: unlocking a monitor happens-before the next lock of it, a write to a volatile field happens-before later reads of it, and Thread.start() and join() create the same ordering.
JVM and performance
18. What are the main JVM memory areas?
The heap (objects, split into young and old generations), thread stacks (frames with local variables), metaspace (class metadata) and the code cache (JIT-compiled code). OutOfMemoryError messages tell you which one filled up.
19. How does garbage collection work at a high level?
The collector finds objects reachable from GC roots (stack variables, static fields) and frees the rest. Most objects die young, so the young generation is collected often and cheaply; survivors move to the old generation. G1 is the default collector.
20. What are common causes of memory leaks in Java?
Ever-growing static collections or caches, listeners that are never removed, ThreadLocal values left in pool threads, and unclosed resources. Find them with a heap dump and a tool like Eclipse MAT or VisualVM.
21. How would you investigate a slow API endpoint?
Measure first: logs with timings, then a profiler or thread dumps. Typical causes are N+1 database queries, missing indexes, calls to slow external services without timeouts, and large JSON payloads. Fix the biggest cause and measure again.
22. What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when code loads a class by name (Class.forName) and it is missing. NoClassDefFoundError means a class that was present at compile time is missing or failed to initialise at run time, often a dependency or classpath problem.
Spring Boot and backend
23. How does Spring Boot auto-configuration decide what to create?
Auto-configuration classes are guarded by conditions such as @ConditionalOnClass and @ConditionalOnMissingBean. If the right library is on the classpath and you have not defined your own bean, Boot creates one with defaults from your properties.
24. Why can @Transactional fail silently?
It is applied through a proxy: calls from within the same class, private methods and checked exceptions (no rollback by default) are the usual surprises. Also, catching an exception inside the method means the transaction never sees it.
25. How do you fix the N+1 problem in JPA?
Use JOIN FETCH in a query, an @EntityGraph, batch fetching, or a DTO projection that loads exactly what is needed. Turn on SQL logging to see the extra queries first.
26. How do you secure a REST API?
HTTPS, authentication with short-lived JWTs or sessions, authorization checks on every endpoint (roles plus ownership checks), input validation, rate limiting on login, no secrets in code, and error messages that do not leak internals.
27. How do you make an endpoint idempotent?
Make repeated identical requests have the same effect as one: PUT and DELETE naturally are; for POST (such as payments) accept an idempotency key, store it, and return the stored result when the same key arrives again.
Design and practice
28. Explain the SOLID principles with examples.
Single responsibility (one reason to change), Open/closed (add behaviour with new classes, not edits), Liskov substitution (subclasses work wherever the parent does), Interface segregation (small focused interfaces), Dependency inversion (depend on interfaces, inject implementations).
29. Which design patterns have you used?
Answer with real cases: Builder for objects with many optional fields, Strategy for swappable pricing or payment rules, Factory to create the right implementation, Singleton via Spring beans, Observer through application events.
30. How do you write unit tests for a service with dependencies?
Use JUnit 5 with Mockito: mock the repository and clients, call the service method, assert the result and verify important interactions. Keep tests fast and independent; test edge cases and failures, not only the happy path.
31. How do you review code?
Check correctness and edge cases first, then readability, naming and tests, then performance and security concerns such as SQL injection or missing authorization. Ask questions rather than demand changes, and keep comments specific.
How answers should sound at this level
- Explain why, not only what: why
ConcurrentHashMapis faster, why constructor injection is better. - Mention a trade-off: every choice costs something (memory, readability, consistency).
- Use your own work: "In our order service we had an N+1 problem; we fixed it with a fetch join and cut the page load from 3 seconds to 300 ms."
- Be honest about what you have not used; then explain how you would approach it.
Frequently asked questions
What is asked in a Java interview for 2 years of experience?
Core Java in depth (collections internals, immutability, exceptions), Java 8+ streams, concurrency basics, JVM memory, Spring Boot with JPA, SQL, plus questions about your projects and a coding problem.
How should I talk about my projects?
Describe the problem, your part, the design choices and one hard bug or improvement with a measurable result. Keep it to two minutes and be ready for follow-up questions.
Is DSA still asked at 2 years of experience?
Usually yes, often medium-level problems on arrays, strings, hash maps, trees or graphs. Keep practising a few problems a week.
Learn it step by step
- How HashMap works inside
- Design your own immutable class
- Group data with groupingBy
- How ConcurrentHashMap works inside
- Combine tasks: thenCombine, allOf and anyOf
- Young and old generations
- What a memory leak means in Java
- Fixes: JOIN FETCH, @EntityGraph and batch fetching
- A Short Project Pitch: Problem, Solution, Your Role
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.