Common Java Interview Questions
These questions appear repeatedly in Java developer interviews from junior through senior levels. Understand the why, not just the answer.
OOP Fundamentals
Q: Explain the four pillars of OOP.
| Pillar | Description | Java Example |
|---|---|---|
| Encapsulation | Hide internal state, expose via methods | Private fields + getters/setters |
| Inheritance | Reuse code through parent-child relationship | class Dog extends Animal |
| Polymorphism | Same interface, different behavior | Method overriding, interface implementations |
| Abstraction | Hide complexity, show essentials | Abstract classes, interfaces |
Q: Abstract class vs Interface?
| Abstract Class | Interface | |
|---|---|---|
| Fields | Any type | public static final constants |
| Methods | Abstract + concrete | Abstract (pre-8), default/static (8+) |
| Inheritance | Single (extends) |
Multiple (implements) |
| Constructor | Yes | No |
| Use when | Shared code + template | Capability contract |
Since Java 8, interfaces can have default and static methods. Prefer interfaces for capabilities; abstract classes when sharing substantial code.
Q: Overloading vs Overriding?
// Overloading — same name, different parameters (compile-time)
class Math {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
// Overriding — subclass replaces parent method (runtime)
class Animal { void speak() { System.out.println("..."); } }
class Dog extends Animal { @Override void speak() { System.out.println("Woof"); } }
equals() and hashCode()
Q: Why override both equals() and hashCode()?
The contract: if two objects are equal, they must have the same hash code. Hash-based collections (HashMap, HashSet) use hashCode for bucket placement and equals for collision resolution.
public record User(int id, String email) {
// Records auto-generate equals/hashCode based on components
}
// Manual implementation
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User user)) return false;
return id == user.id && Objects.equals(email, user.email);
}
@Override
public int hashCode() {
return Objects.hash(id, email);
}
Breaking the contract causes duplicates in HashSet and lost entries in HashMap.
String Pool and Immutability
Q: Why are Strings immutable in Java?
- Security — strings used for file paths, URLs, class loading can’t be modified after validation
- Thread safety — immutable objects are inherently thread-safe
- String pool — interning works because strings can’t change
String a = "hello"; // string pool
String b = "hello"; // same pool reference
String c = new String("hello"); // heap object
System.out.println(a == b); // true (same reference)
System.out.println(a == c); // false (different objects)
System.out.println(a.equals(c)); // true (same content)
String d = c.intern(); // add to pool
System.out.println(a == d); // true
Q: String vs StringBuilder vs StringBuffer?
| Class | Mutable | Thread-safe | Use |
|---|---|---|---|
| String | No | Yes (immutable) | Short literals, infrequent changes |
| StringBuilder | Yes | No | Single-threaded string building |
| StringBuffer | Yes | Yes (synchronized) | Legacy — prefer StringBuilder |
JVM Basics
Q: Explain JVM, JRE, and JDK.
JDK = JRE + development tools (javac, javadoc, debugger)
JRE = JVM + standard libraries (runtime only)
JVM = executes bytecode, manages memory, JIT compilation
Q: Heap vs Stack?
| Stack | Heap | |
|---|---|---|
| Stores | Method frames, local variables, references | Objects, arrays, instance fields |
| Size | Small, fixed per thread | Large, shared |
| GC | Automatic on method return | Garbage collected |
| Thread | Per-thread | Shared across threads |
void method() {
int x = 10; // stack — primitive
User user = new User(); // reference on stack, object on heap
}
Q: What is garbage collection?
GC reclaims heap memory from unreachable objects. Generational GC (G1, ZGC) divides heap into young and old generations — most objects die young.
Tunable with: -Xms, -Xmx, -XX:+UseG1GC, -XX:+UseZGC
Exception Handling
Q: Checked vs Unchecked exceptions?
| Checked | Unchecked | |
|---|---|---|
| Extends | Exception | RuntimeException |
| Must handle | Yes (compile error if not) | No |
| Examples | IOException, SQLException | NullPointerException, IllegalArgumentException |
// Checked — must catch or declare
public void readFile() throws IOException {
Files.readString(Path.of("data.txt"));
}
// Unchecked — no declaration required
public void divide(int a, int b) {
if (b == 0) throw new IllegalArgumentException("Division by zero");
}
Debate: modern codebases often prefer unchecked exceptions for cleaner APIs.
Java 8+ Features
Q: Explain lambda expressions and functional interfaces.
// Functional interface — one abstract method
@FunctionalInterface
interface Operation {
int apply(int a, int b);
}
Operation add = (a, b) -> a + b;
Operation multiply = (a, b) -> a * b;
List<Integer> nums = List.of(1, 2, 3, 4, 5);
nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.forEach(System.out::println); // 4, 8
Built-in functional interfaces: Predicate<T>, Function<T,R>, Consumer<T>, Supplier<T>.
Q: What are records?
public record Point(int x, int y) {
// Auto: constructor, getters, equals, hashCode, toString
}
Point p = new Point(3, 4);
System.out.println(p.x()); // 3
Immutable data carriers — ideal for DTOs and value objects.
Common Coding Questions
Q: Reverse a string.
String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
Q: Find duplicates in an array.
List<Integer> findDuplicates(int[] arr) {
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new LinkedHashSet<>();
for (int n : arr) {
if (!seen.add(n)) duplicates.add(n);
}
return new ArrayList<>(duplicates);
}
Q: Is a string a palindrome?
boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
Preparation Tips
- Practice explaining concepts aloud — interviews test communication
- Write code on paper or whiteboard without IDE autocomplete
- Know time/space complexity of your solutions
- Review your own projects — be ready to discuss design decisions
- Study Collections and Concurrency next