Java Mock Interview

Naveen AnamaneniUpdated · 11 min read

Actors don't rehearse a play by reading the script silently in a chair. They stand up, say the lines out loud, and run the whole scene against the clock, because that is where the forgotten words show up. Interviews work the same way. You may understand HashMap perfectly, but explaining it clearly in two minutes, while someone waits, is a different skill. This page is your rehearsal: 20 of the most common Java interview questions, 40 minutes on the clock, and a model answer to compare with after each one.

How the Mock Interview Works

  1. Press Start on the timer below. You have 40 minutes for 20 questions, so about 2 minutes each.
  2. Read a question and answer it out loud, as if an interviewer were sitting across from you. Don't open the model answer first.
  3. Open the model answer and compare it with what you said.
  4. Mark yourself honestly: Strong if you covered all the key points, Partial if you got some of them, Missed if you didn't know.
  5. Move on, even if you are unhappy with an answer. In a real interview there's no going back either.

Target: 14 or more answers marked Strong. Your score appears at the bottom of the page as you mark.

Mock interview: 40 minutes

Press Start, then answer question 1 out loud. Aim for about 2 minutes per question.

The 20 Questions

1. JDK, JRE and JVM

What is the difference between the JDK, the JRE and the JVM?

Model answer

The JVM runs bytecode: it loads classes, verifies them, interprets them, JIT-compiles the hot code and manages memory. The JRE is the JVM plus the core class libraries needed to run programs. The JDK is the JRE plus the development tools: javac, jar, javap, jshell and jlink. Since Java 11, Oracle no longer ships a separate JRE; you install a JDK, or build a small runtime for your app with jlink. Revise: Difference Between JDK, JRE and JVM.

Your mark for question 1

2. Why String Is Immutable

Why is String immutable?

Model answer

Four reasons. (1) The String pool can safely share one object between many references. (2) Security: file paths, URLs and class names can't be changed after they have been checked. (3) Thread safety without any locks. (4) The hash code can be cached, which makes strings fast HashMap keys. The cost is that every "change" creates a new object, so use StringBuilder for repeated changes. Revise: Why String Is Immutable in Java.

Your mark for question 2

3. Double Equals and Equals

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

Model answer

== compares primitive values, or, for objects, whether two references point to the same object. equals() compares logical equality, as the class defines it: String, the wrapper classes and records compare their contents. The default Object.equals() is the same as ==. A classic trap is comparing Integer values above 127 with ==, which gives false because only -128 to 127 are cached. Revise: String Comparison in Java.

Your mark for question 3

4. Equals and HashCode Contract

What is the equals and hashCode contract, and what breaks if you ignore it?

Model answer

If two objects are equal, they must have the same hash code. Equal hash codes don't require equality, because collisions are allowed. equals must be reflexive, symmetric, transitive and consistent, and x.equals(null) must be false. If you override equals without hashCode, a HashMap or HashSet looks in the wrong bucket: contains returns false for an "equal" key, and duplicates appear. Also, never change a field used in hashCode while the object is a key in a map. Revise: Object Equality and Hash Codes in Java.

Your mark for question 4

5. How HashMap Works

How does HashMap work internally?

Model answer

It keeps an array of buckets, 16 by default. put calls key.hashCode(), mixes the high bits into the low bits (h ^ (h >>> 16)), and picks a bucket with (n - 1) & hash. Keys that land in the same bucket are chained in a linked list. Since Java 8, a bucket with about 8 entries becomes a red-black tree (if the table has at least 64 buckets), so the worst case is O(log n) instead of O(n). When the size passes capacity × load factor (0.75), the table doubles and the entries are spread out again. get finds the bucket by hash, then compares keys with equals. One null key is allowed, and it goes in bucket 0. Revise: HashMap Internal Working.

Your mark for question 5

6. ArrayList or LinkedList

ArrayList or LinkedList: when do you use each?

Model answer

ArrayList is a resizable array: O(1) access by index, amortized O(1) to add at the end, O(n) to insert or remove in the middle, and very friendly to the CPU cache. LinkedList is a doubly linked list: O(1) to add or remove at either end or at an iterator's position, but O(n) access by index and more memory per element. In practice ArrayList wins almost every time, and for a queue or stack, ArrayDeque is better than LinkedList. Revise: Difference Between ArrayList and LinkedList.

Your mark for question 6

7. Checked and Unchecked Exceptions

Checked or unchecked exceptions: when do you create a custom one?

Model answer

Checked exceptions (subclasses of Exception that aren't RuntimeException) must be caught or declared. Use them for recoverable conditions the caller should handle, such as a missing file. Unchecked exceptions (RuntimeException and its subclasses) signal programming errors, such as a null or a bad argument. Create a custom exception when it tells the caller something useful, like InsufficientFundsException. Always keep the original cause (new MyException("message", e)), and never swallow an exception with an empty catch. Revise: Checked vs Unchecked Exceptions and Custom Exceptions in Java.

Your mark for question 7

8. Final, Finally and Finalize

final, finally and finalize: what is the difference?

Model answer

final is a modifier: a final variable can't be reassigned, a final method can't be overridden, and a final class can't be extended. finally is a block that runs after try and catch whether or not an exception happened (unless the JVM stops, for example on System.exit), and is used for cleanup; today, try-with-resources is usually better. finalize() is a deprecated Object method that the garbage collector might call before collecting an object. It is unreliable, so use try-with-resources or a Cleaner instead. Revise: Difference Between Final, Finally and Finalize.

Your mark for question 8

9. Abstract Class or Interface

Abstract class or interface in modern Java?

Model answer

An interface describes a capability that a class has, and a class can implement many. Since Java 8 and 9, interfaces can have default, static and private methods, but they can't hold instance state or have constructors. An abstract class is a partial implementation, with shared state and constructors, and a class can extend only one. Rule of thumb: start with an interface, and add an abstract base class only to share state or code between closely related classes. Use a sealed interface when the set of implementations is fixed. Revise: Difference Between Abstract Class and Interface.

Your mark for question 9

10. Overloading and Overriding

Overloading vs overriding: can you override a static method?

Model answer

Overloading means the same method name with different parameter lists, chosen at compile time. Overriding means a subclass replaces an inherited instance method with the same signature, chosen at runtime from the real object (dynamic dispatch). An overriding method can't reduce visibility or throw broader checked exceptions, and it may return a subtype. Static methods can't be overridden, only hidden: the declared type decides which one runs. Private and final methods can't be overridden either. Revise: Method Overloading vs Overriding.

Your mark for question 10

11. Immutable Classes

How do you create an immutable class?

Model answer

Make the class final (or give it only private constructors), make every field private final, provide no setters, and set everything in the constructor. Copy mutable inputs and outputs defensively (List.copyOf, or a copy of an array). Return a new object from any "changing" method, such as withPrice(...). In modern Java a record does most of this, but you still need to copy mutable components in a compact constructor. Revise: How to Create an Immutable Class in Java.

Your mark for question 11

12. Comparable or Comparator

Comparable or Comparator?

Model answer

Comparable<T> defines the natural order inside the class itself, through compareTo. There's one natural order per class, as with String or LocalDate. Comparator<T> is an external strategy, so you can define many orders without changing the class. The modern style is Comparator.comparing(Employee::dept).thenComparing(Employee::salary, Comparator.reverseOrder()). Keep compareTo consistent with equals, or sorted sets and maps behave in surprising ways. Revise: Difference Between Comparable and Comparator.

Your mark for question 12

13. Fail-Fast and Fail-Safe Iterators

What is the difference between fail-fast and fail-safe iterators?

Model answer

Fail-fast iterators (ArrayList, HashMap) check a modification count and throw ConcurrentModificationException if the collection is structurally changed during iteration, except through the iterator's own remove. This is a best-effort check, not a guarantee. Fail-safe, or weakly consistent, iterators (ConcurrentHashMap, CopyOnWriteArrayList) never throw: they work on a snapshot or tolerate changes while they run, but may not show the latest updates. Revise: Fail-Fast vs Fail-Safe Iterators.

Your mark for question 13

14. Lazy Streams

Intermediate vs terminal stream operations: what does "lazy" mean?

Model answer

Intermediate operations (filter, map, sorted) return a new stream and do nothing yet; they only describe the pipeline. A terminal operation (collect, forEach, count, findFirst) starts the work. Elements flow through the whole pipeline one at a time, and short-circuiting operations (findFirst, limit, anyMatch) can stop early, even on an infinite stream. A stream can be used only once. Revise: Lazy Evaluation and Short-Circuiting in Streams.

Your mark for question 14

15. Map and FlatMap

What is the difference between map and flatMap?

Model answer

map turns each element into exactly one element: a Stream<T> becomes a Stream<R>. flatMap turns each element into a stream of zero or more elements and joins them all into one stream. For example, orders.stream().flatMap(o -> o.items().stream()) gives every item from every order. Optional.flatMap works the same way and avoids an Optional<Optional<T>>. Revise: Stream flatMap in Java.

Your mark for question 15

16. When Not to Use Optional

When should you not use Optional?

Model answer

Optional is designed as a return type for "there may be no result". Avoid it for fields, method parameters and collection elements, and return an empty collection instead of an Optional<List>. Never call get() without checking; prefer orElse, orElseGet, orElseThrow, map and ifPresent. Use orElseGet when the default is expensive to build, because orElse always evaluates its argument. Revise: Optional Best Practices.

Your mark for question 16

17. Synchronized, Locks and Volatile

synchronized, ReentrantLock and volatile: when do you use each?

Model answer

volatile gives visibility and ordering for a single variable, but no atomicity, so use it for flags. synchronized gives mutual exclusion plus visibility; it is simple and releases the lock automatically, even when an exception is thrown. ReentrantLock adds tryLock with a timeout, locking that can be interrupted, fairness and several Conditions, but you must call unlock() in a finally block. For counters, use the atomic classes or LongAdder. Revise: Volatile Keyword in Java and Locks in Java.

Your mark for question 17

18. Deadlock

What is a deadlock, and how do you prevent it?

Model answer

A deadlock is two or more threads each holding a lock while waiting for a lock another one holds, so none of them can continue. Four conditions must all hold: mutual exclusion, hold and wait, no preemption, and circular wait. To prevent it, take locks in one fixed global order, use tryLock with a timeout, keep critical sections small, and don't call unknown code while holding a lock. To diagnose it, take a thread dump (jstack or jcmd <pid> Thread.print), which reports any deadlock it finds. Revise: Deadlock in Java.

Your mark for question 18

19. Virtual Threads

Virtual threads vs platform threads?

Model answer

A platform thread wraps an operating system thread. It is expensive (it reserves about 1 MB of stack by default), so you can have only thousands. A virtual thread is managed by the JVM and runs on a small pool of carrier threads. When it blocks on I/O it unmounts and frees its carrier, so you can run millions. Virtual threads suit I/O-bound, thread-per-request code; they don't make CPU-heavy work faster. Don't pool them: create one per task, and limit access to scarce resources with a Semaphore. Watch for pinning: since Java 24, synchronized no longer pins, but native calls still can. Revise: Platform Threads vs Virtual Threads.

Your mark for question 19

20. Memory and Garbage Collection

Stack vs heap, how does garbage collection work, and can Java leak memory?

Model answer

Each thread's stack holds frames with local variables and references. The shared heap holds the objects. The garbage collector finds objects that are unreachable from the GC roots (thread stacks, static fields and JNI references). It is generational: most objects die young, so the young generation is collected often and cheaply, and survivors are promoted. G1 is the default collector, and ZGC gives very short pauses. Java can still "leak" when objects you no longer need stay reachable: static collections that only grow, caches without eviction, listeners that are never removed, and ThreadLocals in thread pools. You find them with heap dumps and tools such as VisualVM, JFR or Eclipse MAT. Revise: Stack vs Heap Memory in Java and Memory Leaks in Java.

Your mark for question 20

Your Score

Your mock interview score

Mark your answers above, and your score appears here.

Strong answersWhat it meansWhat to do next
17 to 20Interview readyBook real interviews. Keep answers to about 2 minutes, and practice the coding round as well
14 to 16Nearly thereReread the model answers you marked Partial or Missed, then take the mock interview again in a few days
Under 14Not yetWork through the lessons linked from your weaker answers and Core Java Interview Questions, then try again

Was this tutorial helpful?