Java Interview Questions and Answers: 30 Core Theory Questions
Thirty core Java interview questions with short answers: JVM, pass-by-value, String immutability, equals and hashCode, HashMap, generics, GC and concurrency.
- Course: Java study plan
- Module: Interview idioms
- Kind: Lesson
- Reading time: 16 min
- Runtime: OpenJDK 18
What are the most common Java interview questions?
The most common Java interview questions cover JDK vs JRE vs JVM, whether Java is pass-by-value, why strings are immutable, == vs equals, checked vs unchecked exceptions, overloading vs overriding, abstract classes vs interfaces, how HashMap works, type erasure, ArrayList vs LinkedList, garbage collection, start vs run, synchronized vs volatile, and deadlock. Answer each with a one-sentence definition and one consequence.
Lesson
Every Java interview has a theory section, and the questions have not changed in a decade. This lesson is the drill: the thirty questions you will be asked, each with the two-sentence answer an interviewer wants to hear and a pointer to the module that explains it in depth. Read it twice a week before interviews. The answers are deliberately compact — the skill being tested is saying the essential thing first, then stopping so the interviewer can ask the follow-up.
Platform and language basics
- JDK vs JRE vs JVM? The JVM executes bytecode; the JRE is the JVM plus the standard library; the JDK is the JRE plus compiler and tools. (Module 1)
- Why is Java "write once, run anywhere"? Source compiles to platform-neutral bytecode; each platform's JVM interprets and JIT-compiles it. (1)
- Is Java pass-by-value or pass-by-reference? Strictly pass-by-value; for objects the value copied is the reference, so callees can mutate the object but not rebind the caller's variable. (5, 16)
- Why are strings immutable? Safety (they are everywhere — class names, keys, security), the string pool needs sharing, hash code caching, and thread safety for free. (3, 16)
==vsequals? Reference identity versus logical equality;equalsfor strings and boxed numbers, always. (3, 20)final,finally,finalize? Constant/non-overridable/non-extensible; the always-runs block aftertry; the deprecated GC hook — never use. (7, 12, 16)- Checked vs unchecked exceptions? Checked must be declared or caught (recoverable conditions the caller should handle); unchecked (
RuntimeException) signal programming errors. (12) String,StringBuilder,StringBuffer? Immutable; mutable and fast; mutable and synchronised (legacy). Builder in loops. (3)- Autoboxing pitfalls?
Integercache −128..127 makes==lie; boxing allocates;remove(int)vsremove(Object); unboxingnullis an NPE. (2, 16) staticmeans? Belongs to the class, one copy, nothis; static methods cannot be overridden (they hide). (7)
Object orientation
- Overloading vs overriding? Same name different parameters, resolved at compile time by static types; same signature in a subclass, dispatched at run time by the object's class. (5, 8)
- Abstract class vs interface? A class with state and partial implementation, single inheritance; a contract, multiple implementation,
defaultmethods but no instance state. Prefer interfaces; abstract classes for shared state. (8, 9) - Can a constructor be overridden? Called virtually? No — constructors are not inherited; and calling an overridable method from a constructor sees the subclass's fields uninitialised. (7, 8)
- What is polymorphism in Java? A reference of a supertype invoking the runtime type's override — dynamic dispatch through the vtable. (8)
- Composition vs inheritance? Has-a versus is-a; prefer composition — inheritance couples to the parent's implementation and breaks encapsulation. (8)
- What do records give you? Immutable value classes with
equals/hashCode/toString/accessors generated; compact constructors for validation. (10) - Sealed classes? A fixed set of permitted subtypes, enabling exhaustive switches. (9, 19)
Generics and collections
- Type erasure? Generics exist only at compile time; at run time
List<String>isList— nonew T[], noinstanceof List<String>, one class for all instantiations. (13) ? extendsvs? super? Producer extends (read), consumer super (write) — PECS. (13)- How does
HashMapwork? Hash → spread → bucket; chain or tree on collision; resize at 0.75 load; needs consistentequals/hashCode; O(1) average. (14) ArrayListvsLinkedList? Array-backed, O(1) index, amortised O(1) append; node-backed, O(n) index, poor cache behaviour — almost alwaysArrayList. (14)HashMapvsTreeMapvsLinkedHashMap? Unordered O(1); sorted O(log n) with navigation; insertion (or access) order O(1). (14)- Fail-fast iteration? Modifying a collection while iterating throws
ConcurrentModificationException; use the iterator'sremoveorremoveIf. (14) ComparablevsComparator? Natural order on the type versus an external order per use;Integer.compare, never subtraction. (9, 20)
Streams, memory, concurrency
- Intermediate vs terminal operations? Lazy, return a stream, do nothing until a terminal; the terminal runs the pipeline once. Streams are single-use. (15)
- Where do objects and locals live? Heap and thread stack respectively;
StackOverflowErrorversusOutOfMemoryError. (16) - How does garbage collection work? Reachability from roots, generational (young/old), stop-the-world pauses reduced by concurrent collectors (G1 default, ZGC). (16)
- Thread vs Runnable;
startvsrun? Pass aRunnableto aThread;startspawns a thread that callsrun;rundirectly is a plain call. (17) synchronizedvsvolatile? Mutual exclusion plus visibility, for compound updates; visibility only, for a flag or a published immutable reference. (17)- What is a deadlock and how do you avoid it? Threads waiting on each other's locks forever; consistent lock ordering, one lock, or
tryLockwith back-off. (17)
The follow-ups they actually ask
- After 4: "Then how does
StringBuilderexist?" — a separate mutable class;Stringshares nothing with it. - After 9: "So is
Integer.valueOf(127) == Integer.valueOf(127)true?" — yes; 128, no. - After 11: "What is printed?" — a snippet with an overloaded
describe(Animal)/describe(Dog)called with anAnimalreference to aDog: theAnimaloverload (static type), whilea.speak()is theDogoverride (runtime type). Fields are never polymorphic. - After 18: "Then how does
List<String>.getreturn aString?" — the compiler inserts the cast. - After 20: "What if
hashCodealways returns 1?" — everything in one bucket; O(n) lookups, or O(log n) once it treeifies (Java 8+, if keys areComparable). - After 25: "Can you reuse a stream?" — no;
IllegalStateException. - After 29: "Is
volatile int count; count++safe?" — no;AtomicInteger.
How to answer theory questions
Lead with the one-sentence definition, add the one consequence that matters, stop. If you know a version number or a class name, say it — "ConcurrentHashMap, since Java 8 with per-bin locking" beats "there's a concurrent map". Never guess a fact you are unsure of; "I believe it is X, but I would check" is a fine answer and a wrong confident answer is not. When you do not know, connect it to what you do: "I have not used StampedLock, but I know ReadWriteLock and would expect it to be the faster, non-reentrant variant."
Key takeaways
- Thirty questions cover almost every Java theory round; know the two-sentence answer to each.
- Lead with the definition, add one consequence, stop; name classes and versions.
- Expect the follow-up: the cache boundary, the overload-versus-override snippet, the all-ones
hashCode. - Never bluff; connect the unknown to the known.
Common questions
Why are strings immutable in Java?
Because strings are used everywhere — class names, map keys, security checks — immutability makes them safe to share: the string pool can give one object to every user of a literal, the hash code can be cached, and strings pass between threads without synchronisation.
What is the difference between final, finally and finalize in Java?
final makes a variable constant, a method non-overridable or a class non-extensible; finally is the block after try that always runs; finalize is the deprecated garbage-collection hook that should never be used.
How does HashMap work internally in Java?
The key's hashCode is spread and mapped to a bucket; colliding entries share the bucket as a chain, which becomes a tree once it grows long (Java 8+). The table resizes past a 0.75 load factor, and lookups are O(1) on average when equals and hashCode are consistent.
What is the difference between overloading and overriding in Java?
Overloading is one method name with different parameters, chosen at compile time from the arguments' static types. Overriding is a subclass redefining a method with the same signature, chosen at run time from the object's actual class. Fields are never polymorphic.
What is type erasure in Java?
Generic type arguments exist only at compile time: at run time a List<String> is a plain List, so you cannot write new T[] or test instanceof List<String>. The compiler inserts the casts that make get return a String.
What is the difference between String, StringBuilder and StringBuffer?
String is immutable; StringBuilder is mutable and fast; StringBuffer is mutable and synchronised, a legacy class. Use StringBuilder when building a string in a loop, since += copies the whole string each time.
Exercise
Static versus dynamic dispatch
Write class Animal { String name = "animal"; String speak() { return "..."; } }, class Dog extends Animal (field name = "dog", speak() returns Woof) and class Cat extends Animal (name = "cat", Meow). Add three static overloads describe(Animal), describe(Dog), describe(Cat) returning describe(Animal), describe(Dog) and describe(Cat). Read n and n words dog/cat; for each, with Animal a = …, print one line:
<word>: speak=<a.speak()> describe=<describe(a)> cast=<describe(…) after a pattern-instanceof cast to the real type> field=<a.name>
Predict before running: the override is chosen at run time, the overload at compile time, and the field by the static type.
Example: 2 then dog cat →
dog: speak=Woof describe=describe(Animal) cast=describe(Dog) field=animal
cat: speak=Meow describe=describe(Animal) cast=describe(Cat) field=animalIn this module: Interview idioms
- The interview template — input, output, limits
- equals, hashCode and Comparable — the contracts that make collections work
- The pitfalls that fail interviews
- The collections idiom sheet
- Writing clean solutions under time pressure
- The Java theory drill — thirty questions, thirty answers (this lesson)
- Final checkpoint — Interview idioms
← Writing clean solutions under time pressure · Final checkpoint — Interview idioms →