Java interview questions and answers: 25 from core to advanced

These Java interview questions and answers cover the core language first, then collections, exceptions, generics, concurrency, the JVM and streams. Each has a short correct answer and, where it helps, a snippet that compiles and runs on JDK 21 LTS. Newer LTS releases exist; behavior shown here was checked on JDK 21.

What are basic Java interview questions?

Basic Java interview questions cover the JDK, JRE and JVM, == versus equals(), String immutability, autoboxing, abstract classes versus interfaces, overloading versus overriding, and the common collections. Freshers meet them first, and every level gets a few. Questions 1 to 12 below cover them. These core Java interview questions appear in nearly every first round. Tested on JDK 21 (imports and a small Res class assumed where the snippets are fragments).

1. What are the JDK, JRE and JVM?

The JVM runs bytecode. The JRE is the JVM plus the standard libraries. The JDK adds development tools such as javac. Modern distributions ship the JDK, and the JRE is rarely installed on its own.

2. What is the difference between == and equals()?

For objects, == compares references and equals() compares logical equality, if the class overrides it. For primitives, == compares values.

String s1 = "hi", s2 = "hi", s3 = new String("hi");
System.out.println(s1 == s2);       // true  (same pooled literal)
System.out.println(s1 == s3);       // false (different object)
System.out.println(s1.equals(s3));  // true

3. Why is String immutable?

Immutability makes strings safe to share between threads, safe as HashMap keys (the hash can be cached), and safe for the string pool and for security-sensitive values such as file paths. Use StringBuilder to build a string in a loop, because += in a loop creates many temporary strings. StringBuffer is the older synchronized version.

4. What is autoboxing, and what is the Integer cache trap?

Autoboxing converts between int and Integer automatically. Boxed values from -128 to 127 are cached, so == works on small values and fails on larger ones. Always compare boxed values with equals().

Integer a = 127, b = 127, c = 1000, d = 1000;
System.out.println(a == b);       // true
System.out.println(c == d);       // false
System.out.println(c.equals(d));  // true

5. What is the difference between an abstract class and an interface?

A class extends one abstract class but can implement many interfaces. Abstract classes can hold state and constructors. Interfaces describe a capability, and since Java 8 they can have default and static methods. Pick an interface unless you need shared state.

6. What is the difference between overloading and overriding?

Overloading means several methods with the same name and different parameters, chosen at compile time. Overriding means a subclass replaces an inherited method with the same signature, chosen at run time by the actual object type (polymorphism). Use @Override so the compiler catches typos.

What collections questions come up?

7. When do you pick ArrayList over LinkedList?

Almost always ArrayList. It gives O(1) indexed access and good cache behavior. LinkedList only wins for frequent insertion or removal at the ends through its iterator or deque methods, and even then ArrayDeque is usually better.

8. How does HashMap work?

It hashes the key to pick a bucket in an array. Keys in the same bucket are chained, and from Java 8 long chains turn into balanced trees. Lookups are O(1) on average. The map resizes when the load factor (default 0.75) is exceeded. It allows one null key and is not thread-safe.

9. What is the equals() and hashCode() contract?

If two objects are equal by equals(), they must return the same hashCode(). Different hashes are allowed for unequal objects, and equal hashes do not prove equality. If you override one, override the other, or hash-based collections will lose your objects.

final class Point {
    private final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point)) return false;
        Point p = (Point) o;
        return x == p.x && y == p.y;
    }
    @Override public int hashCode() { return Objects.hash(x, y); }
}

Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
System.out.println(set.contains(new Point(1, 2)));  // true

Without hashCode(), that last line would usually print false. A record gives you both methods for free.

10. What is the difference between HashMap, LinkedHashMap and TreeMap?

HashMap has no order and O(1) average access. LinkedHashMap keeps insertion order. TreeMap keeps keys sorted, with O(log n) access, and needs keys that are comparable or a Comparator.

11. What is a fail-fast iterator?

Iterators on ArrayList and HashMap throw ConcurrentModificationException if the collection changes during iteration by anything except the iterator. Remove items safely with iterator.remove() or list.removeIf(...).

List<Integer> l = new ArrayList<>(List.of(1, 2, 3, 4));
l.removeIf(x -> x % 2 == 0);
System.out.println(l);  // [1, 3]

12. What is the difference between Comparable and Comparator?

Comparable defines a class's natural order inside the class (compareTo). Comparator is a separate object that defines another order, for example Comparator.comparing(Person::name).thenComparing(Person::age).

What do they ask about immutability and exceptions?

13. How do you make a class immutable?

Make the class final, make all fields private final, offer no setters, and copy any mutable input or output.

final class Money {
    private final long cents;
    private final List<String> tags;

    Money(long cents, List<String> tags) {
        this.cents = cents;
        this.tags = List.copyOf(tags);  // defensive copy, itself immutable
    }
    List<String> tags() { return tags; }  // add() would throw
}

14. What is the difference between checked and unchecked exceptions?

Checked exceptions (subclasses of Exception other than RuntimeException) must be caught or declared. Unchecked ones (RuntimeException and Error) need not be. Use checked exceptions for recoverable conditions the caller can act on, and unchecked ones for programming errors.

15. What is try-with-resources?

It closes any AutoCloseable automatically, even on exceptions, in reverse order of opening. If both the body and close() throw, the close exception is attached as a suppressed exception.

try (Res r = new Res()) {
    System.out.println("body");
}   // close() runs here: prints "body", then "closed"

16. What does finally do when the try block returns?

The finally block runs before the method returns. Do not return from finally, because it swallows exceptions. Do not confuse it with final (a modifier) or finalize() (deprecated, do not use).

static int f() {
    try { return 1; }
    finally { System.out.println("finally"); }
}
// prints "finally", then f() returns 1

What generics questions should you expect?

17. What is type erasure?

The compiler checks generic types, then removes them. At run time a List<String> is just a List. That is why you cannot write new T(), new T[10] or instanceof List<String>.

18. What are bounded types and wildcards (PECS)?

"Producer extends, consumer super": use ? extends T when you only read from a structure, and ? super T when you only write to it.

static <T extends Comparable<T>> T max(List<T> list) {
    T best = list.get(0);
    for (T t : list) if (t.compareTo(best) > 0) best = t;
    return best;
}

static double sumAll(List<? extends Number> nums) {
    double s = 0;
    for (Number n : nums) s += n.doubleValue();
    return s;
}
// max(Arrays.asList(3, 9, 4)) -> 9; sumAll(List.of(1, 2.5)) -> 3.5

What are the Java concurrency interview questions?

19. How do you create and run threads?

Prefer an ExecutorService over creating Thread objects by hand. It reuses threads and lets you shut down cleanly. CompletableFuture chains async steps. Java 21 added virtual threads for large numbers of blocking tasks.

20. What is the difference between synchronized, volatile and atomic classes?

synchronized gives mutual exclusion and visibility. volatile gives visibility and ordering for one variable, but not atomic updates, so count++ on a volatile field is still a race. AtomicInteger gives lock-free atomic updates.

AtomicInteger c = new AtomicInteger();
ExecutorService ex = Executors.newFixedThreadPool(4);
for (int i = 0; i < 1000; i++) ex.submit(c::incrementAndGet);
ex.shutdown();
ex.awaitTermination(5, TimeUnit.SECONDS);
System.out.println(c.get());  // always 1000

21. What is a deadlock, and how do you avoid it?

Two or more threads each hold a lock the other needs, so none can continue. Avoid it by taking locks in one fixed global order, holding locks for as short a time as possible, and using tryLock with a timeout. A thread dump (jstack) shows the cycle.

22. How is ConcurrentHashMap different from Collections.synchronizedMap?

synchronizedMap wraps every call in one lock. ConcurrentHashMap allows many readers and writers at once, and offers atomic methods such as merge and computeIfAbsent. It does not allow null keys or values.

What do Java interviews ask about the JVM and garbage collection?

23. What are the JVM memory areas?

The heap holds objects and is shared by all threads. Each thread has its own stack of frames with local variables. Metaspace holds class metadata (it replaced PermGen in Java 8). The heap is divided into young and old generations.

24. How does garbage collection work?

The collector frees objects that are no longer reachable from GC roots (stack variables, static fields). Most objects die young, so new objects start in the young generation and survivors move to the old generation. G1 has been the default collector since Java 9, and ZGC targets very short pauses. A memory leak in Java usually means objects still reachable by mistake, such as a static map that only grows. Tools: heap dumps and a profiler.

What about streams and lambdas?

25. How do streams work, and what are the traps?

A stream is a lazy pipeline: intermediate steps (filter, map) do nothing until a terminal step (collect, sum) runs. A stream can be used once. Avoid side effects inside a pipeline, and measure before using parallelStream().

List<String> names = List.of("ann", "bob", "amy", "cy");

names.stream().filter(n -> n.startsWith("a"))
     .map(String::toUpperCase)
     .collect(Collectors.toList());            // [ANN, AMY]

names.stream().collect(
     Collectors.groupingBy(String::length, Collectors.counting()));  // {2=1, 3=3}

Java interview questions for freshers, 3 years and 5 years of experience

This table covers junior and senior Java interviews in one place.

LevelWhat to prepareWhat interviewers look for
Freshers (junior)Questions 1 to 12. The four OOP ideas (encapsulation, inheritance, polymorphism, abstraction) with a real example each. Small programs on strings, arrays and lists, written without an IDE.Correct definitions, small examples that run, and the right collection for the job.
3 yearsQuestions 7 to 22. How HashMap works, streams, ExecutorService, unit tests with JUnit, and one project explained from request to database.Internals, synchronized and executors, heap versus stack, and what GC does.
5 years and seniorQuestions 19 to 25 in depth, plus trade-offs: thread pool sizing, a race you found, GC symptoms you diagnosed, API design and code review.Why a design was chosen and what breaks if it changes: races and deadlocks, memory visibility, GC logs and heap dumps, system design, mentoring and incidents.

If the posting names Spring, JPA or microservices, add them for the 3 and 5 year levels.

For senior roles, expect these core Java interview questions to turn into follow-ups: "what happens under load?" and "how would you test that?" Pair this list with technical interview tips for the full loop, and practice talking while you code, as in live coding interview tips. Preparing for Python as well? See Python interview questions.

If you get stuck mid-answer

Practice is the best fix. Write each snippet above yourself until you can explain it without looking, and no tool replaces that. Hintly is a desktop app for Mac and Windows that listens during a live interview and shows a suggested answer in a small overlay, built from your own notes such as your CV or resume. The overlay is hidden from screen share. It is pre-launch, so you can join the waitlist. Check any rules an employer has about tools in interviews first. More in our AI interview assistant guide.

Questions

What are the important questions in Java?

The difference between == and equals, how HashMap works, the equals and hashCode contract, String immutability, checked versus unchecked exceptions, abstract classes versus interfaces, synchronized versus volatile, and how garbage collection works. These come up at almost every level.

How do I prepare for a Java interview in a week?

Spend the first days on collections, equals and hashCode, exceptions and concurrency basics. Then write small programs for each topic instead of only reading. Finish with two or three coding tasks on a blank editor, aloud.

Which Java version should I know?

Know Java 8 features well (lambdas, streams, Optional), since many questions still use them. Then read the long-term-support releases the posting names, such as records and virtual threads in Java 21.

Do I need to know Spring for a Java interview?

Many Java jobs use Spring, but a core Java round usually tests the language and standard library. If the posting names Spring or Hibernate, expect a separate round.

How is a senior Java interview different?

Senior interviews ask why, not only what. Expect trade-offs, failure cases in concurrent code, memory and garbage collection behavior in production, and design questions. See the level table below.

Your next interview, handled.

Hintly is almost ready. Leave your email and we’ll tell you the day you can download it.

Mac and Windows · No spam