Skip to content
Tutorials Center
My learning

Topics

Lesson 201 of 201 · Practice and Review

Java Interview Questions

60 common Java interview questions with clear answers, from == vs equals and OOP to HashMap internals, streams, concurrency, garbage collection and Java 25.

Java interviews test two things at once: whether you know how the language and the JVM actually behave, and whether you can explain that knowledge clearly and briefly. This page collects 60 questions that come up again and again, grouped by level (Junior, Mid, Senior) and by topic, each with a concise, accurate answer you can put into your own words.

Try to answer each question out loud before you open it. If you can't explain an idea in a few sentences, follow the link to its lesson and review it. Several questions ask you to read code and predict the output; make your guess first, then press Run. The levels are a rough guide: senior interviews still start with junior questions, they just expect deeper follow-ups.

Tip: a short, correct answer plus a tiny example beats a long recital. Mention trade-offs ("this is faster, but uses more memory", "this is safe, but blocks") whenever you can: weighing options is what separates mid-level answers from junior ones, and senior answers add when not to use something.

Junior level

Platform and language basics

What are the JDK, the JRE and the JVM?

The JVM (Java Virtual Machine) runs compiled bytecode: it loads classes, verifies them, interprets and JIT-compiles them to machine code, and manages memory with a garbage collector. The JRE (Java Runtime Environment) is the JVM plus the standard class library, everything needed to run programs. The JDK (Java Development Kit) is the JRE plus development tools such as javac, jar, javadoc, jshell and jlink. Since Java 11 vendors ship only JDKs; a trimmed runtime is built with jlink when needed. See How Java Works.

What is the difference between primitive and reference types?

Java has eight primitives (byte, short, int, long, float, double, char, boolean) that hold their value directly and can't be null. Everything else is a reference type: the variable holds a reference to an object on the heap, and it can be null. Assigning a primitive copies the value; assigning a reference copies the reference, so both variables point to the same object. Generics need reference types, which is why List<Integer> boxes int values. See Primitive Data Types and Wrapper Classes.

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

For primitives, == compares values. For objects, == compares references: whether both sides are the very same object. equals() compares contents as defined by the class; Object.equals defaults to ==, but String, the wrapper classes, collections and records override it. Always compare strings, boxed numbers and other value objects with equals (or Objects.equals when either side may be null). See Strings and The Object Class.

Predict what each line prints before you run it:

Java Code reading: string identity

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Why are lines 1 and 2 true but line 3 false?

"ja" + "va" and prefix + "va" (where prefix is a final variable initialized with a constant) are compile-time constant expressions: the compiler joins them into the literal "java", which refers to the same pooled string. suffix isn't final, so "ja" + suffix is computed at run time and creates a new String object. Line 4 compares characters and is always true. The lesson: never let correctness depend on string pooling.

Why is String immutable?

Several reasons reinforce each other. Security: strings carry file paths, URLs, class names and SQL; if they could change after a check, the check would be useless. Pooling: identical literals can safely share one object. Hashing: a string can cache its hash code, which makes it a fast, reliable HashMap key. Thread safety: immutable objects can be shared between threads without locks. The cost is that every "modification" creates a new object, which is why loops should use StringBuilder. See Strings and Immutable Classes.

What is the difference between String, StringBuilder and StringBuffer?

String is immutable. StringBuilder is a mutable, resizable character buffer for building text efficiently, especially in loops; it isn't thread-safe. StringBuffer is the older version with every method synchronized, which makes it slower and rarely useful, since a buffer is almost never shared between threads. Use StringBuilder by default; for simple joins, String.join or Collectors.joining read better. See StringBuilder and StringBuffer, StringJoiner and StringTokenizer.

Is Java pass-by-value or pass-by-reference?

Always pass-by-value. For primitives the method receives a copy of the value. For objects it receives a copy of the reference: it can call methods that change the object the caller sees, but reassigning the parameter (list = new ArrayList<>()) only changes the local copy, never the caller's variable. That's why a swap(a, b) method can't swap two caller variables in Java. See Parameters and Return Values.

What does static mean, and why is main traditionally static?

A static member belongs to the class, not to any object: one copy of a static field is shared by all instances, and a static method is called without an object (Math.max(a, b)). Static methods can't use this or instance fields directly. main was static so the JVM could call it without creating an object first. Since Java 25, the launcher also accepts instance main methods and void main() without parameters; it creates the object for you. See Static Members and The main Method.

What is the difference between final, finally and finalize?

They're unrelated. final is a modifier: a final variable can't be reassigned, a final method can't be overridden, a final class can't be extended. finally is the block after try that runs whether or not an exception was thrown, used for cleanup (today usually replaced by try-with-resources). finalize() was a method the garbage collector might call before reclaiming an object; it's unpredictable and slow, deprecated since Java 9 and deprecated for removal since Java 18. Use try-with-resources or java.lang.ref.Cleaner instead. See The final Keyword.

Exceptions

What is the difference between checked and unchecked exceptions?

Checked exceptions extend Exception but not RuntimeException; the compiler forces you to catch them or declare them with throws. They model recoverable conditions outside the program's control: IOException, SQLException. Unchecked exceptions extend RuntimeException and usually signal programming bugs: NullPointerException, IllegalArgumentException, IndexOutOfBoundsException. Error (such as OutOfMemoryError) is also unchecked and normally shouldn't be caught. See Throwing Exceptions.

Does finally always run?

It runs after the try block completes normally, after a return, after break or continue, and when an exception is thrown, whether caught or not. It does not run if the JVM stops first: System.exit(), a crash, the process being killed, or a thread that never finishes the try. A return inside finally is a trap: it replaces the original return value and silently discards any exception in flight, as the next example shows. See Exceptions and try-catch.

Java Code reading: finally and return

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What does this print, and why is second() dangerous?

It prints finally in first(), then 1, then 2. In first(), the return value 1 is computed, the finally block runs, and then the method returns. In second(), the return 2 in finally overrides the pending exception, so the IllegalStateException vanishes without a trace. Code reviewers treat return, break or throw in a finally block as a bug.

What is try-with-resources, and what are suppressed exceptions?

try (var in = Files.newBufferedReader(path)) { ... } automatically calls close() on every resource that implements AutoCloseable, in reverse order of opening, even when the body throws. If the body throws and close() throws too, the body's exception is the one propagated, and the close() exception is attached to it as a suppressed exception (getSuppressed()) instead of replacing it. That fixes the classic finally-based cleanup bug where the close error hid the real one. See try-with-resources.

Object-oriented programming

What are the four pillars of OOP, in one sentence each?

Encapsulation: keep state private and expose behavior through methods, so the object protects its own invariants. Abstraction: expose what an object does and hide how, through interfaces and abstract classes. Inheritance: a class reuses and specializes another (class Dog extends Animal), an is-a relationship. Polymorphism: code written against a supertype works with any subtype, and the right overriding method is chosen at run time. See Object-Oriented Programming.

What is the difference between overloading and overriding?

Overloading means several methods in the same class with the same name but different parameter lists; the compiler picks one at compile time from the static types of the arguments. Overriding means a subclass provides its own implementation of an inherited instance method with the same signature; the JVM picks it at run time from the object's actual class (dynamic dispatch). Overriding can't reduce visibility or throw broader checked exceptions, and may return a subtype (covariant return). See Method Overloading and Polymorphism.

Java Code reading: overload vs override

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Why does describe(pet) pick the Animal overload but still print "Woof"?

Two separate decisions happen. Choosing which overload is done by the compiler from the declared type of the argument: pet is declared as Animal, so describe(Animal) is chosen (the same goes for the cast in the third line). Choosing which sound() happens at run time from the actual object, which is a Dog, so "Woof" is returned. Output: describe(Animal): Woof, describe(Dog): Woof, describe(Animal): Woof.

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

An abstract class can have constructors, instance fields (state), and methods with any access level; a class can extend only one. An interface defines a contract: abstract methods plus default, static and private methods, but no instance state (its fields are public static final constants); a class can implement many. Use an interface for a capability many unrelated classes can have (Comparable, Runnable), and an abstract class to share state and code among closely related classes, such as a template method. Today interfaces are the default choice. See Abstract Classes and Interfaces.

Can you override a static method or a private method?

No. A static method in a subclass with the same signature hides the parent's method: which one runs depends on the compile-time type, not on the object, so there's no polymorphism (and @Override on it is a compile error). A private method isn't visible to subclasses, so a method with the same name in a subclass is a completely new method. Final methods can't be overridden either.

Are constructors inherited? What is the default constructor?

Constructors are not inherited; every class declares its own, and each one starts by calling a superclass constructor, either explicitly with super(...) or implicitly with super(). If a class declares no constructor at all, the compiler adds a no-argument default constructor. As soon as you write any constructor, that default disappears, which is why a subclass fails to compile when the parent has only constructors with parameters and the child doesn't call one of them. See Constructors and The super Keyword.

Why "favor composition over inheritance"?

Inheritance couples a subclass tightly to its parent's implementation: changes in the parent can break subclasses (the "fragile base class" problem), and you inherit every public method, wanted or not. Composition means holding another object as a field and delegating to it, a has-a relationship. It lets you swap implementations, combine behaviors and expose only what you choose. Use inheritance only for a true is-a relationship where the subclass can stand in for the parent everywhere. See Composition, Aggregation and Association.

Mid level

Collections

When would you choose ArrayList over LinkedList?

Almost always. ArrayList stores elements in a contiguous array: O(1) access by index, amortized O(1) appends, and excellent CPU cache behavior. LinkedList is a doubly linked list: O(n) access by index, a node object per element (several times the memory), and poor locality. Its O(1) insertion only helps when you already hold an iterator at the position. For queues and stacks, ArrayDeque beats both. See ArrayList, LinkedList and Choosing the Right Collection.

How does HashMap work internally?

It keeps an array of buckets (16 by default). To store a key it calls hashCode(), mixes the high bits into the low bits, and uses hash & (capacity - 1) as the bucket index. Entries that land in the same bucket form a linked list; since Java 8 a bucket with 8 or more entries is converted to a balanced red-black tree (if the table has at least 64 buckets), so heavy collisions cost O(log n) instead of O(n). When the number of entries exceeds capacity × load factor (0.75), the table doubles and entries are redistributed. Lookups call equals() only on keys in the selected bucket. Average get and put are O(1). See How HashMap Works Inside.

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

Equal objects (per equals) must have equal hash codes; unequal objects may share a hash code, but fewer collisions mean better performance. equals must be reflexive, symmetric, transitive, consistent and return false for null. If you override equals without hashCode, two equal objects usually land in different buckets, so HashSet keeps duplicates and HashMap.get misses keys. A related bug: changing a field used in hashCode while the object is inside a hash collection, as the next example shows. See The Object Class.

Java Code reading: a mutated key

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Why can't the set find the list it obviously contains?

The list was stored in the bucket for the hash of [1, 2]. After key.add(3) its hash code changes, so contains looks in a different bucket and finds nothing, even for an equal list. A linear search with anyMatch still finds it because it ignores hashing. Output: [[1, 2, 3]], false, false, true. Use immutable keys (strings, records with immutable components, List.of).

How do HashMap, Hashtable and ConcurrentHashMap differ?

HashMap isn't thread-safe and allows one null key and null values. Hashtable is a legacy class whose every method is synchronized (one lock for the whole table) and allows no nulls; don't use it in new code. ConcurrentHashMap is built for concurrency: reads don't block, writes lock only a single bucket (using CAS where possible), iterators are weakly consistent (they never throw ConcurrentModificationException), and compute, merge and putIfAbsent are atomic. It rejects null keys and values so that get returning null always means "absent". See Concurrent Collections and Legacy Collections.

What is the difference between Comparable and Comparator?

Comparable<T> is implemented by the class itself (compareTo) and defines its natural order, such as numbers ascending or strings alphabetically. Comparator<T> is a separate object that defines any order, so a class can be sorted many ways without changing it: Comparator.comparing(Person::lastName).thenComparing(Person::firstName).reversed(). Both return negative, zero or positive; compute it with Integer.compare, never subtraction, which can overflow. Natural order should be consistent with equals, or sorted sets behave oddly. See Comparable and Comparator.

What are fail-fast iterators, and when do you get a ConcurrentModificationException?

Iterators of ArrayList, HashMap and most non-concurrent collections are fail-fast: they track a modification count and throw ConcurrentModificationException on the next step if the collection was structurally changed by anything other than the iterator itself. The classic cause is calling list.remove(x) inside a for-each loop, in a single thread. Fixes: iterator.remove(), removeIf, or collecting changes and applying them afterwards. Concurrent collections use weakly consistent (or snapshot) iterators instead. See Iterators.

What is the difference between List.of, Arrays.asList and Collections.unmodifiableList?

List.of(...) creates a truly immutable list: no add, remove or set, and no null elements. Arrays.asList(array) returns a fixed-size view of the array: set works and writes through to the array, but add and remove throw UnsupportedOperationException. Collections.unmodifiableList(list) is a read-only view of another list: you can't modify it through the view, but changes to the original still show through. List.copyOf makes an immutable snapshot. See Immutable Collections and Utility Methods.

Generics

What is type erasure, and what limitations does it cause?

Generic type information exists only at compile time. The compiler checks types, inserts casts, and then erases type parameters to their bounds (usually Object), so List<String> and List<Integer> are the same class at run time. Consequences: you can't write new T() or new T[], can't use instanceof List<String>, can't overload methods that differ only by type argument, and can't use primitives as type arguments. Erasure was chosen for compatibility with pre-generics code. See Type Erasure.

What do ? extends and ? super mean (PECS)?

List<? extends Number> accepts a list of Number or any subtype; you can read Numbers from it but not add (except null), because the exact type is unknown. List<? super Integer> accepts a list of Integer or any supertype; you can add Integers but only read Objects. The mnemonic is PECS: Producer extends, Consumer super. Collections.copy(List<? super T> dest, List<? extends T> src) uses both. See Bounded Types and Wildcards.

What does this print? (wrappers and autoboxing)
Java
Integer a = 1000, b = 1000;
IO.println(a == b);              // false: two different Integer objects
IO.println(a <= b && a >= b);    // true: <= and >= unbox to int
Long id = 10L;
IO.println(id.equals(10));       // false: 10 is boxed to Integer, not Long
Map<Long, String> names = new HashMap<>(Map.of(1L, "one"));
IO.println(names.get(1));        // null: the key 1 is an Integer

Integer.valueOf caches only -128 to 127, so == on larger boxed values compares two distinct objects. Relational operators unbox, but == between two wrappers doesn't. equals across wrapper types is always false, a common bug with Map<Long, ...> keys. Unboxing a null wrapper throws NullPointerException. See Wrapper Classes and Autoboxing.

Modern Java (8 and later)

What is a functional interface, and how do lambdas relate to it?

A functional interface has exactly one abstract method (default and static methods don't count), for example Runnable, Comparator, Function<T, R> or Predicate<T>. A lambda or method reference is a compact implementation of that single method, and its type comes from the context (target typing). @FunctionalInterface is optional and makes the compiler check the one-method rule. Lambdas can capture local variables only if they're effectively final. See Lambdas, Functional Interfaces and Method References.

What are intermediate and terminal stream operations? What does "lazy" mean?

Intermediate operations (filter, map, sorted, distinct, limit) return a new stream and do nothing on their own. A terminal operation (collect, toList, forEach, reduce, count, findFirst) starts the pipeline and produces a result. Laziness means elements flow through the whole pipeline one at a time, only as far as needed: stream.filter(...).findFirst() stops at the first match. A stream can be consumed only once. See Streams.

What is the difference between map and flatMap?

map transforms each element into exactly one element: a Stream<Order> mapped with Order::lines becomes a Stream<List<Line>>. flatMap transforms each element into a stream and flattens all of them into one: orders.stream().flatMap(o -> o.lines().stream()) gives a Stream<Line>. The same idea exists on Optional: flatMap avoids Optional<Optional<T>>. See Advanced Streams.

How should Optional be used, and how shouldn't it?

Use Optional<T> as a return type for "there may be no result", such as findById, and handle it with map, filter, orElse, orElseGet, orElseThrow or ifPresentOrElse. Don't use it for fields, method parameters or collection elements, don't return null from a method declared to return Optional, and avoid get() without a check (prefer orElseThrow()). Return an empty collection instead of Optional<List<T>>. See Optional.

What are records, and when should you use them?

A record (Java 16) is a concise, shallowly immutable data class: record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors x() and y(), and equals, hashCode and toString based on all components. A compact constructor validates or normalizes input. Records are final, can't extend other classes and can't declare extra instance fields, but they can implement interfaces and have methods. Use them for DTOs, value objects, map keys and multiple return values. See Records.

What do sealed classes add to pattern matching?

A sealed type lists every permitted subtype: sealed interface Shape permits Circle, Square {}. The compiler then knows the hierarchy is closed, so a switch over a Shape with a case for every subtype is exhaustive and needs no default. If someone adds a subtype later, every switch that doesn't handle it stops compiling, which is much safer than a default branch that silently swallows the new case. Combined with records and record patterns (case Circle(double r) ->), this gives Java algebraic data types. See Sealed Classes and Pattern Matching.

What are the headline features of the recent LTS releases, 17, 21 and 25?

Java 17: sealed classes, plus the records, text blocks, switch expressions and instanceof patterns finalized in 14 to 16. Java 21: virtual threads, pattern matching for switch, record patterns, and sequenced collections (getFirst, getLast, reversed). Java 25: compact source files with instance main methods and the IO class, module import declarations, flexible constructor bodies (statements before super(...)), and scoped values. Structured concurrency is still a preview feature in 25. See Java Versions and History.

Senior level

Concurrency

What is the difference between start() and run(), and between Runnable and Callable?

thread.start() creates a new thread of execution that then calls run(); calling run() directly just executes the method on the current thread, with no concurrency at all. Runnable.run() returns nothing and can't throw checked exceptions; Callable<V>.call() returns a value and may throw. Submitting a Callable to an ExecutorService gives a Future<V> for the result and any exception. See Threads and Executors.

What is a race condition? Show one.

A race condition is a bug where the result depends on the timing of threads. count++ looks atomic but is three steps (read, add, write), so two threads can read the same value and one update is lost. Fixes: synchronized, a Lock, an AtomicInteger/LongAdder, or not sharing mutable state at all. Run the next example a few times: the plain counter is wrong by a different amount each time. See Synchronization and Race Conditions and Atomic Variables.

Java Code reading: a lost update

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is the difference between synchronized and volatile? What is happens-before?

synchronized provides mutual exclusion (one thread at a time holds the monitor) and visibility (everything written before releasing a lock is visible to the next thread that acquires it). volatile provides only visibility and ordering for a single variable: every read sees the latest write, but compound actions like count++ are still not atomic. Typical volatile use: a stop flag or a safely published reference. Happens-before is the Java Memory Model rule that defines when one thread's writes are guaranteed visible to another: unlock → later lock of the same monitor, volatile write → later read, Thread.start(), Thread.join(), and others. Without such an edge, a thread may see stale values forever.

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

A deadlock happens when threads wait for each other forever, for example thread 1 holds lock A and waits for B while thread 2 holds B and waits for A. All four conditions must hold: mutual exclusion, hold-and-wait, no preemption and a circular wait. Prevent it by breaking one: always acquire locks in a global order, use tryLock with a timeout and back off, hold locks for as short a time as possible, and avoid calling unknown code while holding a lock. A thread dump (jstack, jcmd <pid> Thread.print) reports Java-level deadlocks. See Deadlocks, Livelocks and Starvation.

What is the difference between wait() and sleep()?

Thread.sleep(ms) pauses the current thread for a time and keeps any locks it holds. object.wait() must be called while holding that object's monitor; it releases the monitor and waits until another thread calls notify/notifyAll on the same object (or a timeout or interrupt). Because of spurious wakeups, wait() must always be called in a loop that rechecks the condition. In modern code, prefer BlockingQueue, CountDownLatch or Condition over raw wait/notify. See wait and notify.

Why use a thread pool, and how do you size one?

Creating a platform thread is expensive (an OS thread and about a megabyte of stack reserved), so creating one per task wastes resources and an unbounded number can exhaust memory. An ExecutorService reuses a fixed set of threads, queues work, and gives you Futures and orderly shutdown. For CPU-bound work, about as many threads as cores (Runtime.getRuntime().availableProcessors()). For blocking I/O, more threads help; on Java 21+ the better answer is usually virtual threads. Always shut pools down (close() or shutdown() plus awaitTermination), and prefer bounded queues in servers. See Executors and Thread Pools.

What does CompletableFuture give you over Future?

A plain Future can only be polled or blocked on with get(). CompletableFuture lets you compose asynchronous steps without blocking: thenApply transforms a result, thenCompose chains another async call, thenCombine joins two independent ones, allOf/anyOf wait for groups, and exceptionally/handle recover from errors. orTimeout and completeOnTimeout add deadlines. Pass your own executor for blocking work, because the default is the shared common pool. See CompletableFuture.

What are virtual threads, and when do they help?

Virtual threads (Java 21) are lightweight threads managed by the JVM rather than the OS. Many virtual threads are mounted on a small pool of carrier platform threads; when one blocks on I/O, it's unmounted and the carrier runs another. You can create millions, so the simple thread-per-request style scales again: Executors.newVirtualThreadPerTaskExecutor(). They help with blocking I/O-bound workloads, not CPU-bound ones. Don't pool them, and limit access to scarce resources with a Semaphore instead. Since Java 24, blocking inside synchronized no longer pins the carrier thread; native calls still do. See Virtual Threads and Structured Concurrency.

JVM and memory

What lives on the stack and what lives on the heap?

Each thread has its own stack of frames, one per active method call, holding local variables, primitive values and references; it's freed automatically when the method returns, and too-deep recursion throws StackOverflowError. Objects and arrays live on the shared heap, managed by the garbage collector; running out throws OutOfMemoryError. Class metadata lives in Metaspace (native memory, which replaced PermGen in Java 8). The JIT's escape analysis can avoid heap allocation for objects that never leave a method. See Memory and Garbage Collection.

How does garbage collection decide what to free? Name some collectors.

An object is garbage when it's no longer reachable from GC roots (local variables of live threads, static fields, JNI references); reference cycles don't matter. Most collectors are generational: most objects die young, so the young generation is collected often and cheaply, and long-lived objects are promoted to the old generation. G1 is the default since Java 9, balancing throughput and pause times by collecting regions. ZGC (generational since Java 21) and Shenandoah do most work concurrently for very short pauses on large heaps; Parallel maximizes throughput; Serial suits tiny heaps. See Memory and Garbage Collection.

Can a Java program leak memory?

Yes. The GC frees only unreachable objects, so a leak is memory that's still referenced but no longer needed. Classic causes: static collections or caches that only grow, listeners and callbacks that are never removed, ThreadLocal values in pooled threads, mutated keys stuck in a HashMap, unclosed resources, and class loader leaks in application servers. Diagnose with heap dumps (jcmd <pid> GC.heap_dump) and a tool such as Eclipse MAT, or with Java Flight Recorder. Bounded caches, weak references (WeakHashMap) and try-with-resources prevent most of them.

How does class loading work?

Classes are loaded lazily, on first active use. The bootstrap loader loads core java.base classes, the platform loader loads other JDK modules, and the application (system) loader loads your classpath or module path. Loaders use parent delegation: they ask the parent first, so nobody can replace java.lang.String. Then come linking (verification of the bytecode, preparation of static fields, resolution of references) and initialization, which runs static initializers exactly once, thread-safely. Frameworks and application servers create their own loaders to isolate and reload code. See JVM Architecture and Class Loading.

What is the JIT compiler, and why do benchmarks need warm-up?

The JVM starts by interpreting bytecode, profiles which methods and loops are hot, and compiles those to optimized machine code with the JIT: tiered compilation uses the fast C1 compiler first and the heavily optimizing C2 later. C2 inlines methods, removes unneeded checks, and can even eliminate allocations, using the profile to make speculative optimizations it can undo if assumptions break. Early iterations therefore run much slower than steady state, so naive timing measures the interpreter and compiler. Use JMH for microbenchmarks. See Java Performance Tips.

Design and best practices

How do you write a thread-safe singleton?

The simplest robust way is an enum with one constant: enum Config { INSTANCE; ... }. The JVM guarantees one instance, thread-safe initialization, and protection against reflection and serialization tricks. For a lazily created class, use the holder idiom: a private static nested class holds the instance, and class initialization (which is thread-safe) happens on first access. Double-checked locking also works, but only with a volatile field. Also consider whether you need a singleton at all: dependency injection is easier to test. See Creational Design Patterns.

How do you design an immutable class?

Make the class final (or give it private constructors), make all fields private final, set them in the constructor, provide no setters, and make defensive copies of mutable inputs and outputs (List.copyOf(items), never return the internal array). Methods that "change" the object return a new instance (withPrice(...)). Immutable objects are automatically thread-safe, make safe map keys, and are easy to reason about. A record with immutable components does most of this for you. See Immutable Classes.

Explain the SOLID principles briefly.

Single responsibility: a class should have one reason to change. Open/closed: extend behavior by adding code (new implementations), not by editing working code. Liskov substitution: a subtype must work anywhere its supertype is expected, without surprises. Interface segregation: prefer small, focused interfaces over one big one. Dependency inversion: depend on abstractions, and inject them, rather than creating concrete dependencies inside a class. Mention them with an example from your own code; interviewers care more about judgment than definitions. See Object-Oriented Design Principles.

More questions: collections, strings and I/O

A second set of questions that interviewers like because each one has a crisp "difference" answer and a small trap.

Collections and iteration

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

A fail-fast iterator (ArrayList, HashMap, HashSet and most java.util collections) checks an internal modification counter, modCount, while iterating. If the collection is structurally changed by anything other than the iterator itself, the next call throws ConcurrentModificationException. It is a best-effort bug detector, not a guarantee, so never build logic that depends on catching it. A fail-safe iterator (more precisely a weakly consistent one, as in ConcurrentHashMap, or a snapshot one, as in CopyOnWriteArrayList) never throws it: it iterates over a copy, or tolerates concurrent changes and may or may not show them. To remove while iterating, use Iterator.remove() or removeIf. See Iterators and Concurrent Collections.

Java Code reading: modifying while iterating

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is the difference between Collection and Collections?

Collection is an interface, the root of List, Set and Queue. Collections is a utility class full of static helpers: sort, reverse, shuffle, unmodifiableList, synchronizedList, emptyList, frequency, max. The names differ by one letter, and so do their jobs: one describes what a group of objects can do, the other operates on groups. (Map is not a Collection, which is another classic follow-up.) See Collections Utilities.

How do PriorityQueue and TreeSet differ?

Both keep elements ordered by natural order or a Comparator, but they promise different things. PriorityQueue is a binary heap: peek and poll return the smallest element in O(1) and O(log n), and it allows duplicates, but iterating it does not give sorted order (only the head is guaranteed). TreeSet is a red-black tree: it holds no duplicates (equal means compareTo == 0), iterates in full sorted order, and supports range queries (first, floor, ceiling, subSet) in O(log n). Use a heap for "next most urgent task", a tree set for "sorted unique values". See Queues and Deques and TreeMap and TreeSet.

Java Code reading: heap order vs tree order

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is the difference between a singly and a doubly linked list?

Each node in a singly linked list stores the value and a pointer to the next node, so you can only walk forward and removing a node needs its predecessor. A doubly linked list also stores a pointer to the previous node: you can walk both ways and unlink a node you already hold in O(1), at the price of an extra reference per node. Java's LinkedList is doubly linked, which is why it implements Deque. In practice ArrayList or ArrayDeque beats it almost every time because of cache locality. See LinkedList.

How do HashSet and TreeSet differ?

HashSet uses a hash table and hashCode/equals: O(1) average add, remove and contains, no ordering guarantee, and it permits one null. TreeSet uses a balanced tree and compareTo or a Comparator: O(log n) operations, sorted iteration, navigation methods, and no null with natural ordering. Equality also differs: two elements are duplicates in a TreeSet when the comparator returns 0, even if equals says otherwise, which is a common source of lost elements. See HashSet and TreeMap and TreeSet.

Threads and objects

What is the difference between sleep() and wait()?

Thread.sleep(ms) is a static method that pauses the current thread for a time and keeps every lock it holds. Object.wait() is an instance method that must be called while holding that object's monitor (inside synchronized), releases that monitor while waiting, and ends when another thread calls notify() or notifyAll() (or on timeout, an interrupt, or a spurious wakeup, so it belongs in a loop that rechecks the condition). Use sleep to pause, wait to coordinate. Modern code usually prefers java.util.concurrent tools (BlockingQueue, CountDownLatch, Condition). See Thread Lifecycle and Inter-Thread Communication.

What is the difference between this() and super()?

this(...) calls another constructor of the same class, so you can chain constructors and keep initialization in one place. super(...) calls a constructor of the parent class. Either call must be the first statement in a constructor (Java 25 relaxes this slightly: statements that don't touch this may come before), you can use only one of them, and you can't use both in the same constructor. If you write neither, the compiler inserts super() for you, which fails to compile when the parent has no no-argument constructor. See Constructors and Inheritance.

Exceptions and strings

How does an exception propagate, and what does System.exit do inside finally?

If a method doesn't catch an exception, it unwinds that frame (running finally blocks on the way) and hands the exception to its caller, and so on up the call stack until a catch handles it. If none does, the thread's uncaught-exception handler prints the stack trace and the thread ends. A finally block runs whether the try ends normally, by return, or by exception, so a return inside finally silently swallows an exception, which is why you should never write one. The one thing that stops finally is the JVM itself ending: System.exit(n) (or a crash or a killed process) terminates the JVM without running the remaining finally blocks. See Exceptions and Stack Traces and Exception Chaining.

Java Code reading: propagation and finally

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

How would you validate a password with a regular expression?

Describe the rules first, then express each as a lookahead so they can be checked independently from the same starting position. For "at least 8 characters, with a lowercase letter, an uppercase letter, a digit and a symbol": ^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\d)(?=.*[^\p{L}\d\s]).{8,}$. Each (?=...) looks ahead without consuming input, and the final .{8,} enforces length. In an interview, also say that regex rules are a weak policy on their own: modern guidance (NIST) favors length and a blocklist of common passwords over arbitrary composition rules, and that you must never log or store the password itself, only a salted hash from a purpose-built algorithm such as Argon2 or bcrypt. See Regular Expressions.

Java Code reading: a lookahead password check

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Input and output

What is the difference between Reader and InputStream?

InputStream reads bytes; Reader reads characters. Bytes are the truth on disk and on the network, and characters are what text means. A Reader decodes bytes using a charset, so use it for text and an InputStream for binary data such as images, archives and serialized objects. The bridge is InputStreamReader(stream, charset): always pass the charset explicitly (StandardCharsets.UTF_8), because relying on the platform default is a classic portability bug. The same split exists for output: OutputStream and Writer. See Input and Output Streams.

Java Code reading: bytes versus characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Animal pet = new Dog(); There are overloads describe(Animal) and describe(Dog), and Dog overrides sound(). Which runs for describe(pet)?

    The overload is chosen at compile time from the declared type Animal; the overriding method is chosen at run time from the actual object, a Dog.
  2. 2. Why does ConcurrentHashMap reject null keys and values?

    In a single-threaded HashMap you can call containsKey to disambiguate, but in a concurrent map the entry could change between the two calls. Banning null keeps "null means absent" reliable.
  3. 3. Which statement about volatile is correct?

    volatile gives visibility and ordering for one variable. Compound actions such as count++ still need synchronized, a Lock or an atomic class.
  4. 4. String s = "ja"; String t = s + "va"; What is t == "java"?

    Only constant expressions (literals and final variables initialized with constants) are joined at compile time and pooled. s isn't final, so the concatenation runs at run time and creates a new String.

Summary

  • Junior questions check the foundations: JDK/JRE/JVM, primitives vs references, == vs equals, string immutability, pass-by-value, static, exceptions and the OOP basics of overloading, overriding, interfaces and constructors.
  • Mid-level questions focus on collections (HashMap internals, equals/hashCode, fail-fast iterators, immutable lists), generics (erasure, PECS), autoboxing traps and modern Java: lambdas, streams, Optional, records, sealed types and recent LTS features.
  • Senior questions go under the hood: race conditions, the memory model, deadlocks, pools, CompletableFuture, virtual threads, stack vs heap, garbage collectors, class loading, the JIT, and design judgment.
  • A good answer is short, correct, backed by a tiny example and honest about trade-offs.

You've reached the end of the Java course. Keep your skills sharp with the exercises and the 40 classic programs, keep the cheat sheet close, and when you're ready for databases, web services and Spring, continue with Advanced Java. Happy coding!