Java Interview Questions and Answers
JVM fundamentals, OOP, collections, concurrency and Spring concepts.
Whether you are preparing for entry-level Java interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.
1 What is the difference between an interface and an abstract class? Easy
- An interface declares a contract. It supports abstract methods plus default and static methods (Java 8+), private methods (Java 9+) and constants. A class can implement many interfaces.
- An abstract class is a partially implemented base class. It can hold state (fields), constructors and any mix of abstract and concrete methods. A class extends only one.
Choose an interface to define capabilities across unrelated types and to keep inheritance flexible. Choose an abstract class to share implementation and state among closely related subclasses.
2 Compare ArrayList, LinkedList and HashMap. Medium
- ArrayList: array-backed, O(1) random access, amortised O(1) append, O(n) insertion/removal in the middle. Best default for ordered lists.
- LinkedList: doubly linked, O(1) insertion/removal at the ends or given a node, O(n) random access and poor cache locality. Rarely the best choice in practice; ArrayDeque is preferred for queues.
- HashMap: hash table with average O(1) get/put, no ordering guarantee, one null key allowed. Collisions are handled with buckets that treeify to red-black trees past a threshold. Use LinkedHashMap for insertion order and TreeMap for sorted keys.
Other essentials: HashSet is a HashMap key set; ConcurrentHashMap for thread-safe maps; choose initial capacity and load factor to avoid rehashing.
3 Explain equals and hashCode contract. Medium
Rules:
- If a.equals(b) is true then a.hashCode() == b.hashCode() must be true.
- If two objects are unequal, their hash codes may still collide (allowed).
- equals must be reflexive, symmetric, transitive and consistent.
- Override both together, or hash-based collections (HashMap, HashSet) misbehave.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User u)) return false; // pattern matching (Java 16+)
return id == u.id && Objects.equals(email, u.email);
}
@Override
public int hashCode() { return Objects.hash(id, email); }
Mutable fields used in equals/hashCode are a classic bug: mutating them after insertion corrupts the collection.
4 What is Spring dependency injection and why use it? Medium
Dependency injection means a component receives its collaborators from outside rather than creating them itself. The Spring container builds and wires the object graph from annotations such as @Component, @Service and @Repository, injecting through constructor, setter or field.
@Service
public class OrderService {
private final PaymentGateway gateway;
public OrderService(PaymentGateway gateway) { this.gateway = gateway; }
}
Benefits: loose coupling, easier testing with mocks, centralised configuration and lifecycle management. Constructor injection is preferred because dependencies are explicit, objects can be immutable and missing beans fail fast at startup. Spring Boot adds auto-configuration and a starter-based dependency model.
5 How does the Java memory model and garbage collection work? Hard
Memory is divided into heap (shared objects) and per-thread stacks (frames, locals). The heap has a young generation (Eden plus two survivor spaces) and an old generation.
GC roots (stack references, statics, JNI references) mark reachable objects; everything else is collectible. Minor GC copies surviving young objects between survivor spaces and promotes long-lived ones to old gen. Major/full GC handles old gen and can pause the application.
Collectors: Serial, Parallel, G1 (default in recent JDKs, region-based with pause targets), ZGC and Shenandoah for very low pause times. Tuning knobs include heap size (-Xmx), pause goals (-XX:MaxGCPauseMillis) and region size. Diagnose with jstat, GC logs, JFR and heap dumps.
6 What causes a deadlock and how do you prevent it? Hard
A deadlock needs four conditions: mutual exclusion, hold-and-wait, no preemption and circular wait.
Classic case: thread A locks X then waits for Y while thread B locks Y then waits for X.
Prevention:
- Establish a global lock ordering and always acquire in that order.
- Use tryLock with a timeout and back off, or lock-free structures.
- Keep critical sections small and avoid calling external code while holding a lock.
- Prefer higher-level concurrency utilities (java.util.concurrent) over manual synchronized.
- Use immutable objects and message passing where possible.
Diagnose with thread dumps (jstack) and JConsole, which detect deadlock cycles.
Frequently Asked Questions About Java Interviews
What do hiring managers evaluate in Java technical rounds?
Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.
What are the best interview tips for practicing Java questions?
Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.