Java course menu
Intermediate Java Interview Questions and Answers
Intermediate Java interview questions with answers: equals and hashCode contract, HashMap internals, ArrayList vs LinkedList, HashMap vs TreeMap, checked vs unchecked exceptions, abstract class vs interface, Comparable vs Comparator, fail-fast iterators, immutability, and records.
On this page
- Objects and OOP
- 1. What is the contract between equals() and hashCode()?
- 2. Abstract class vs interface: when would you use each?
- 3. What is polymorphism in Java?
- 4. How do you make a class immutable?
- 5. What are records, and when should you use them?
- Collections
- 6. How does HashMap work internally?
- 7. ArrayList vs LinkedList?
- 8. HashMap vs TreeMap vs LinkedHashMap?
- 9. Comparable vs Comparator?
- 10. What is a fail-fast iterator?
- Exceptions
- 11. Checked vs unchecked exceptions?
- 12. What is try-with-resources?
- Short coding questions
- 13. Count the frequency of each word.
- 14. Find the first non-repeated character.
- Next steps
These questions test whether you understand how Java's core library and object model work underneath. Interviewers look for precise answers with a reason and, ideally, a small example.
Objects and OOP#
1. What is the contract between equals() and hashCode()?#
Show solution
If two objects are equals, they must return the same hashCode. (Different objects may share a hash code; that is a collision, which is allowed.) Hash-based collections first use hashCode to find a bucket, then equals to find the key, so overriding equals without hashCode breaks them:
import java.util.HashSet;
import java.util.Set;
class PointNoHash {
final int x, y;
PointNoHash(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof PointNoHash p && p.x == x && p.y == y;
}
}
record Point(int x, int y) {} // generates both equals and hashCode
public class Main {
public static void main(String[] args) {
Set<PointNoHash> broken = new HashSet<>();
broken.add(new PointNoHash(1, 2));
System.out.println(broken.contains(new PointNoHash(1, 2)));
Set<Point> fixed = new HashSet<>();
fixed.add(new Point(1, 2));
System.out.println(fixed.contains(new Point(1, 2)));
}
}false
true2. Abstract class vs interface: when would you use each?#
Show solution
- An abstract class can have state (fields), constructors and concrete methods; a class can extend only one. Use it for closely related classes that share code and state.
- An interface defines a capability; since Java 8 it can have
defaultandstaticmethods, but no instance state; a class can implement many. Use it for types and capabilities shared by unrelated classes, and to declare variables (List, notArrayList).
Modern designs usually start with an interface, adding an abstract base class only to share implementation.
3. What is polymorphism in Java?#
Show solution
The ability to treat objects of different classes through a common supertype, with each object running its own overridden behaviour. Java chooses the implementation of an instance method at run time from the actual object (dynamic dispatch). Overloading, by contrast, is resolved at compile time.
4. How do you make a class immutable?#
Show solution
Make the class final, all fields private final, set them in the constructor, provide no setters, return new objects from "modifying" methods, and make defensive copies of mutable inputs and outputs (for example List.copyOf). Records give you most of this automatically for simple data classes.
5. What are records, and when should you use them?#
Show solution
A record (Java 16+) is a compact, immutable data class: record Point(int x, int y) {} generates private final fields, a constructor, accessors (x()), and value-based equals, hashCode and toString. Use records for values defined by their data (DTOs, coordinates, results with several parts). They cannot extend classes or have mutable instance fields.
Collections#
6. How does HashMap work internally?#
Show solution
A HashMap keeps an array of buckets. For put(key, value) it computes key.hashCode(), spreads the bits, and picks a bucket index. Entries with the same bucket form a linked list, which since Java 8 turns into a balanced tree when a bucket grows large (so the worst case is O(log n) instead of O(n)). get finds the bucket the same way and compares keys with equals. When the number of entries exceeds capacity × load factor (0.75 by default), the table doubles and entries are redistributed (rehashing). Average get/put is O(1).
7. ArrayList vs LinkedList?#
Show solution
ArrayList is backed by a resizable array: O(1) access by index, amortized O(1) add at the end, O(n) insert/remove in the middle (elements shift), and compact memory. LinkedList is a doubly linked list: O(1) add/remove at the ends or at an iterator, but O(n) get(i) and much higher memory overhead. In practice ArrayList wins almost always; use ArrayDeque for queues and stacks.
8. HashMap vs TreeMap vs LinkedHashMap?#
Show solution
9. Comparable vs Comparator?#
Show solution
Comparable<T> is implemented by the class itself (compareTo) and defines its single natural order. A Comparator<T> is a separate object defining any order, built easily with Comparator.comparing(...).thenComparing(...).reversed(). Use Comparable for an obvious natural order, and comparators for everything else.
10. What is a fail-fast iterator?#
Show solution
Iterators of most collections (ArrayList, HashMap) throw ConcurrentModificationException if the collection is structurally modified during iteration by anything other than the iterator itself:
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
try {
for (Integer n : nums) {
if (n % 2 == 0) nums.remove(n);
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}
nums.removeIf(n -> n % 2 == 0); // the safe way
System.out.println(nums);
}
}ConcurrentModificationException
[1, 3]Concurrent collections such as CopyOnWriteArrayList and ConcurrentHashMap have fail-safe (weakly consistent) iterators instead.
Exceptions#
11. Checked vs unchecked exceptions?#
Show solution
Checked exceptions (subclasses of Exception but not RuntimeException, such as IOException) must be caught or declared with throws; they represent recoverable conditions the caller should consider. Unchecked exceptions (RuntimeException and subclasses such as NullPointerException and IllegalArgumentException) need not be declared; they usually indicate programming errors. Errors (such as OutOfMemoryError) are serious problems that applications should not catch.
12. What is try-with-resources?#
Show solution
A try (Resource r = ...) statement automatically calls close() on resources implementing AutoCloseable when the block ends, even after an exception, in reverse order of declaration. Exceptions thrown while closing are attached as suppressed exceptions to the main one. It replaces error-prone finally { close(); } code.
Short coding questions#
13. Count the frequency of each word.#
Show solution
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> freq = new TreeMap<>();
for (String w : "to be or not to be".split(" ")) {
freq.merge(w, 1, Integer::sum);
}
System.out.println(freq);
}
}{be=2, not=1, or=1, to=2}O(n log k) with TreeMap; O(n) with HashMap if order does not matter. A stream version is Collectors.groupingBy(w -> w, Collectors.counting()).
14. Find the first non-repeated character.#
Show solution
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
static Character firstUnique(String s) {
Map<Character, Integer> counts = new LinkedHashMap<>(); // keeps insertion order
for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
for (Map.Entry<Character, Integer> e : counts.entrySet()) {
if (e.getValue() == 1) return e.getKey();
}
return null;
}
public static void main(String[] args) {
System.out.println(firstUnique("swiss") + " " + firstUnique("aabb"));
}
}w nullNext steps#
Continue with the Advanced questions, or practise in Coding Challenges.
Finished this lesson?