PrepStack › Backend › Core Java

Core Java interview cheat sheet

Language core, OOP, collections internals, Java 8–21 and the JVM

Core Java rounds check that you know how the language and the JVM really behave: pass-by-value, == vs equals, the String pool, the equals/hashCode contract, exceptions, generics, and how HashMap works inside. Senior rounds add modern Java (records, sealed types, pattern matching, Java 21) and JVM memory, GC and class loading. Read the 15-minute revision first, run through the output puzzles, then switch to Quiz mode and answer out loud.

15-minute revision

  1. JDK = JRE + dev tools (javac, jar, jshell). JRE = JVM + class library. JVM runs bytecode, with an interpreter plus JIT (C1/C2).
  2. Java is always pass-by-value. For objects the value copied is the reference, so you can mutate the caller's object but never reassign it.
  3. Integer caches -128 to 127: Integer a = 127, b = 127; a == b is true, but for 128 it is false. Always compare wrappers with equals.
  4. Strings are immutable and literals live in the String pool (on the heap since Java 7). new String("x") makes a new object. Use StringBuilder in loops.
  5. If you override equals, you must override hashCode. Equal objects must have equal hash codes, or hash-based collections break.
  6. Interfaces can have default and static methods (Java 8) and private methods (Java 9). Abstract classes can have state and constructors; interfaces cannot have instance fields.
  7. Checked exceptions (IOException) must be caught or declared; unchecked ones extend RuntimeException. try-with-resources closes in reverse order and keeps close errors as suppressed.
  8. A return in finally overrides the try return and swallows exceptions. finally does not run after System.exit.
  9. Generics are erased at runtime. PECS: Producer extends, Consumer super. List<Integer> is not a List<Number>.
  10. HashMap: array of buckets, index = (n - 1) & (h ^ h >>> 16), load factor 0.75, a bucket becomes a red-black tree at 8 entries (if capacity ≥ 64).
  11. ArrayList = resizable array (O(1) get, grows 1.5x). LinkedList = doubly linked list; rarely faster in practice. Use ArrayDeque for stacks and queues.
  12. Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException; fail-safe / weakly consistent ones (CopyOnWriteArrayList, ConcurrentHashMap) do not.
  13. Streams are lazy, single-use and need a terminal operation. Optional is for return values, not fields or parameters.
  14. Records (16), sealed classes (17), pattern matching for instanceof (16) and switch (21), text blocks (15), var (10). Java 21 and Java 25 are the current LTS releases.
  15. JVM memory: heap (objects, GC-managed), stack per thread (frames, locals), metaspace (class metadata, native memory, replaced PermGen in Java 8). G1 is the default GC since Java 9; ZGC targets sub-millisecond pauses.
  16. Class loaders: Bootstrap → Platform → Application, with parent delegation. A class is identified by its name plus its loader.

Platform & language basics

JDK vs JRE vs JVM, bytecode & JIT

You write .java, javac turns it into bytecode, and the JVM runs that bytecode on any OS.

  • JVM: a spec plus an implementation (HotSpot is the usual one) that loads, verifies and executes bytecode, and manages memory and threads.
  • JRE: the JVM plus the standard class library. Since Java 11 Oracle no longer ships a separate JRE; you use the JDK or build a trimmed runtime with jlink.
  • JDK: the JRE plus developer tools such as javac, jar, javadoc, jshell, jcmd and jfr.
  • Write once, run anywhere: bytecode is platform-neutral. The JVM itself is platform-specific.
  • HotSpot starts by interpreting bytecode, then the JIT compiles hot methods to native code (C1 quickly, C2 with heavy optimisation). This is called tiered compilation.
  • java Main.java (Java 11+) compiles and runs a single source file in memory, which is handy for scripts and demos.

Interview questions

  • What is the difference between JDK, JRE and JVM?
  • Why is Java platform independent?
  • What is the JIT compiler?

Pass-by-value (always)

Java copies every argument. For objects, the copy is a reference to the same object.

  • Primitives: the method gets a copy of the value. Changing it never affects the caller.
  • Objects: the method gets a copy of the reference. Both point to the same object, so mutations are visible to the caller.
  • Reassigning the parameter (p = new X()) only changes the local copy. The caller still sees the old object.
  • That is why you cannot write a swap(a, b) method that swaps the caller's variables in Java.
  • Immutable types (String, Integer) behave like values because you can't mutate them; any “change” creates a new object.

Interview questions

  • Is Java pass-by-value or pass-by-reference?
  • Can you write a method that swaps two Integer variables of the caller?
  • A method sets list = null on its parameter. What happens to the caller's list?

Primitives, wrappers, autoboxing & the Integer cache

8 primitives hold raw values; wrapper classes box them as objects so they can live in collections and be null.

  • Primitives: byte short int long float double char boolean. They have defaults (0, false) as fields and cannot be null.
  • Wrappers (Integer, Long, ...) are immutable objects. Autoboxing converts int → Integer via Integer.valueOf; unboxing calls intValue().
  • Integer.valueOf returns cached objects for -128..127 (the JLS requires it). Byte, Short, Long and Character (0..127) cache too; Float and Double do not.
  • Unboxing a null wrapper throws NullPointerException. This often hides in map.get(key) assigned to an int.
  • Integer overflow wraps silently: Integer.MAX_VALUE + 1 is Integer.MIN_VALUE. Use Math.addExact to get an exception instead.
  • float/double are binary floating point. Use BigDecimal (built from a String) for money.

Interview questions

  • Why is Integer a = 127, b = 127; a == b true but false for 128?
  • What is autoboxing and what can go wrong?
  • Why use BigDecimal for money?

String immutability, the String pool & StringBuilder

Strings never change. Literals are shared through the pool. Build strings in loops with StringBuilder.

  • String is final and immutable. Methods like concat, replace and toUpperCase return a new String.
  • Why immutable: safe to share and cache (the pool), thread-safe, safe as HashMap keys (hash is cached), and safe for security-sensitive values like class names and paths.
  • String literals are interned in the String pool. Compile-time constant expressions ("ja" + "va") are pooled too; strings built at runtime are not, unless you call intern().
  • == compares references; equals compares characters. Always use equals (or "lit".equals(x) to be null-safe).
  • StringBuilder is mutable and not synchronized (fast). StringBuffer is the old synchronized version; you rarely need it.
  • Since Java 9, compact strings store Latin-1 text as one byte per char, and + concatenation compiles to an invokedynamic call instead of a fixed StringBuilder chain.

Interview questions

  • Why is String immutable in Java?
  • How many objects does String s = new String("hello") create?
  • What is the difference between == and equals for strings?
  • String vs StringBuilder vs StringBuffer?

static, final & access modifiers

static belongs to the class, final means “cannot change”, and access modifiers control who can see a member.

  • static fields and methods belong to the class, not to instances. Static methods cannot use this and cannot be overridden (only hidden).
  • Static initializer blocks run once, when the class is initialized. Instance initializer blocks run before the constructor body on every new.
  • final variable: assigned once. A final reference cannot point elsewhere, but the object can still change.
  • final method: cannot be overridden. final class: cannot be extended (String, Integer).
  • static final primitives and Strings initialised with constants are compile-time constants; they are inlined into other classes, so changing them needs a recompile of the users.
  • A static nested class has no link to an outer instance; an inner class (non-static) holds a hidden reference to the outer object, which can cause memory leaks.

Interview questions

  • Can you override a static method?
  • What is the order of initialization when you create an object?
  • Does final make an object immutable?

OOP in Java

OOP pillars, overloading vs overriding

Encapsulation, inheritance, polymorphism and abstraction. Overloading is chosen at compile time; overriding at runtime.

  • Encapsulation: private fields plus methods that keep the object valid. Abstraction: expose what an object does, hide how.
  • Inheritance: extends one class (single inheritance of state), implements many interfaces. Prefer composition when it is not a true “is-a”.
  • Overloading: same name, different parameter lists, in the same class. Resolved at compile time from the declared argument types.
  • Overriding: subclass redefines an instance method with the same signature. Resolved at runtime (dynamic dispatch) from the actual object.
  • Fields and static methods are not polymorphic; they use the reference's declared type.
  • Overload resolution order: exact match → widening → boxing → varargs.

Interview questions

  • Difference between overloading and overriding?
  • Why doesn't Java support multiple inheritance of classes?
  • Composition vs inheritance?

Abstract class vs interface (default, static, private methods)

An abstract class shares state and code in a hierarchy; an interface defines a capability many unrelated classes can have.

  • Abstract class: can have constructors, instance fields, any access level, and both abstract and concrete methods. A class extends only one.
  • Interface: fields are implicitly public static final; methods are public abstract unless marked default, static or private. A class can implement many.
  • default methods (Java 8) let you add behaviour to an interface without breaking existing implementations, e.g. Collection.stream().
  • static interface methods are helpers called on the interface name (List.of, Comparator.comparing). They are not inherited by implementing classes.
  • private interface methods (Java 9) share code between default methods without exposing it.
  • If a class inherits the same default method from two interfaces, it must override it and can call A.super.m() to pick one. A method from a superclass always wins over an interface default.

Interview questions

  • When would you choose an abstract class over an interface?
  • Why were default methods added in Java 8?
  • What happens if a class implements two interfaces with the same default method?

equals() and hashCode() contract

Equal objects must have equal hash codes. Break this and HashMap/HashSet lose your objects.

  • Default Object.equals is identity (==). Override it for value objects.
  • equals must be reflexive, symmetric, transitive, consistent, and x.equals(null) must be false.
  • hashCode rule: if a.equals(b) then a.hashCode() == b.hashCode(). The reverse is not required (collisions are allowed).
  • Hash collections first find the bucket by hashCode, then check equals. Wrong hashCode means the search looks in the wrong bucket.
  • Use the same fields in both methods, prefer immutable fields, and use Objects.equals / Objects.hash or let a record generate them.
  • instanceof vs getClass() in equals: getClass() keeps symmetry with subclasses; instanceof is fine for final classes or records.

Interview questions

  • What is the contract between equals and hashCode?
  • What happens if you override equals but not hashCode?
  • What happens if hashCode always returns the same constant?

Exceptions & generics

Exceptions: checked vs unchecked, try-with-resources, finally quirks

Checked exceptions are part of the method signature; unchecked ones are programming errors. Use try-with-resources for anything closeable.

  • Hierarchy: Throwable → Error (JVM problems like OutOfMemoryError, don't catch) and Exception. RuntimeException and its subclasses are unchecked; all other Exceptions are checked.
  • Checked exceptions must be caught or declared with throws; the compiler enforces it. They model recoverable conditions (IOException, SQLException).
  • try-with-resources (Java 7) closes every AutoCloseable automatically, in reverse order, even when the body throws. Close failures are attached as suppressed exceptions.
  • finally always runs after try/catch, except on System.exit, a JVM crash or a killed thread. A return or throw in finally replaces the original result or exception.
  • Multi-catch catch (IOException | SQLException e) and precise rethrow reduce boilerplate. Catch blocks must go from specific to general.
  • Wrap low-level exceptions with a cause (new ServiceException("msg", e)) so the stack trace is not lost.

Interview questions

  • Difference between checked and unchecked exceptions?
  • Difference between final, finally and finalize?
  • What does try-with-resources do if both the body and close() throw?
  • When does a finally block not execute?

Generics, type erasure & wildcards (PECS)

Generics give compile-time type safety; at runtime the type arguments are erased.

  • Generics move ClassCastExceptions from runtime to compile time and remove manual casts.
  • Type erasure: the compiler checks types, then replaces T with its bound (Object or e.g. Comparable) and inserts casts. List<String> and List<Integer> share one Class at runtime.
  • Because of erasure you cannot do new T(), new T[], instanceof List<String>, use primitives as type arguments, or overload m(List<String>) with m(List<Integer>).
  • Generics are invariant: List<Integer> is not a List<Number>. Arrays are covariant (Integer[] is an Object[]) and fail at runtime with ArrayStoreException.
  • PECS: Producer extends, Consumer super. Read from List<? extends Number>; write to List<? super Integer>. Collections.copy(List<? super T> dst, List<? extends T> src) is the classic example.
  • Bounded type parameter: <T extends Comparable<? super T>> means T can compare to itself or a supertype.

Interview questions

  • What is type erasure?
  • Explain PECS with an example.
  • Why can't you add an Integer to a List<? extends Number>?
  • Why can't you create a generic array like new T[10]?

Collections

Collections hierarchy, ArrayList vs LinkedList

List keeps order and duplicates, Set keeps unique items, Map maps keys to values, Queue/Deque handle FIFO/LIFO.

  • Collection → List (ArrayList, LinkedList), Set (HashSet, LinkedHashSet, TreeSet), Queue/Deque (ArrayDeque, PriorityQueue, LinkedList). Map is a separate hierarchy (HashMap, LinkedHashMap, TreeMap).
  • ArrayList: backed by an array. O(1) random access, amortised O(1) append, O(n) insert/remove in the middle. Grows by about 1.5x.
  • LinkedList: doubly linked list. O(1) add/remove at a known node, O(n) get(i). More memory per element and poor cache locality, so it is rarely faster in practice.
  • HashSet is a HashMap with dummy values. LinkedHashSet/LinkedHashMap keep insertion order. TreeSet/TreeMap are red-black trees, sorted, O(log n).
  • ArrayDeque is the recommended stack and queue (faster than Stack and LinkedList). PriorityQueue is a binary heap: poll returns the smallest item.
  • List.of, Set.of, Map.of (Java 9) are immutable and reject nulls. Arrays.asList is fixed-size but allows set.

Interview questions

  • ArrayList vs LinkedList: which do you use and why?
  • Difference between HashSet, LinkedHashSet and TreeSet?
  • How does HashSet ensure uniqueness?

HashMap internals: hashing, buckets, resize & treeification

An array of buckets; the hash picks a bucket; collisions go into a list that becomes a red-black tree when it gets long.

  • put(k, v): compute h = k.hashCode(), spread it with h ^ (h >>> 16), then index = (n - 1) & hash (n is a power of two, so this is a fast modulo).
  • Empty bucket: store a new node. Otherwise walk the bucket: same hash and equals → replace value; else append a new node.
  • Default capacity 16, load factor 0.75. When size exceeds capacity × loadFactor (12), the table doubles and entries are redistributed.
  • On resize each entry either stays at index i or moves to i + oldCapacity, decided by one extra hash bit. Java 8 keeps the relative order of nodes.
  • Treeification (Java 8): a bucket with 8+ nodes becomes a red-black tree if the table has at least 64 buckets (otherwise the table resizes instead). It turns back into a list at 6.
  • One null key is allowed (always bucket 0). HashMap is not thread-safe; use ConcurrentHashMap for shared access.

Interview questions

  • How does HashMap work internally?
  • What changed in HashMap in Java 8?
  • Why is the capacity always a power of two?
  • What happens if you mutate a key after putting it in a HashMap?

Fail-fast vs fail-safe iterators & ConcurrentHashMap

Normal collections throw when modified during iteration; concurrent collections let you iterate a snapshot or a live, weakly consistent view.

  • Fail-fast iterators (ArrayList, HashMap, ...) check a modCount. If the collection changed structurally outside the iterator, the next next() throws ConcurrentModificationException. It is best-effort, not a guarantee.
  • Safe ways to remove while iterating: iterator.remove(), removeIf, or collect and remove afterwards.
  • Fail-safe / weakly consistent iterators never throw CME. CopyOnWriteArrayList iterates a snapshot; ConcurrentHashMap iterates the live table and may or may not see concurrent updates.
  • ConcurrentHashMap (Java 8+): no global lock and no segments. Empty bucket inserts use CAS; other writes lock only the bucket's first node; reads are lock-free using volatile reads.
  • CHM rejects null keys and values, because get returning null must clearly mean “absent” in concurrent code.
  • Use atomic compound methods: compute, merge, putIfAbsent, computeIfAbsent. if (!map.containsKey(k)) map.put(k, v) is a race.

Interview questions

  • Difference between fail-fast and fail-safe iterators?
  • How do you remove elements from a list while iterating?
  • How is ConcurrentHashMap thread-safe without locking the whole map?
  • Why doesn't ConcurrentHashMap allow null?

Modern Java (8 → 21)

Lambdas, functional interfaces, method refs & Comparator

A lambda is a short implementation of an interface with one abstract method. Comparator is the one you will use most.

  • A functional interface has exactly one abstract method (default and static methods don't count). @FunctionalInterface makes the compiler check it.
  • Core ones in java.util.function: Function<T,R>, BiFunction, Consumer<T>, Supplier<T>, Predicate<T>, UnaryOperator<T>, BinaryOperator<T>, plus primitive versions like IntPredicate.
  • Lambdas can capture local variables only if they are effectively final. They have no own this; this means the enclosing instance.
  • Method references: static (Integer::parseInt), bound instance (str::length), unbound instance (String::toUpperCase), constructor (ArrayList::new).
  • Comparable (compareTo, in the class itself) defines the natural order. Comparator (compare, a separate object) defines any number of custom orders.
  • Build comparators with Comparator.comparing(...), .thenComparing(...), .reversed(), nullsFirst(...).

Interview questions

  • What is a functional interface? Give examples.
  • Difference between Comparable and Comparator?
  • Why must captured variables be effectively final?
  • Lambda vs anonymous inner class?

Streams API & Optional

A stream is a lazy pipeline: source → intermediate operations → one terminal operation.

  • Intermediate operations (filter, map, flatMap, sorted, distinct, peek) are lazy and return a new stream. Nothing runs until a terminal operation (collect, forEach, reduce, count, findFirst).
  • Streams don't modify the source and can be consumed only once.
  • Elements flow one at a time through the whole pipeline, and short-circuit ops (findFirst, anyMatch, limit) stop early.
  • Collectors: toList, toSet, toMap (throws on duplicate keys unless you pass a merge function), groupingBy, partitioningBy, joining, counting.
  • map is one-to-one; flatMap turns each element into a stream and flattens them. Java 16 added stream.toList() (unmodifiable).
  • Optional is a return type for “maybe no result”. Use map, filter, orElse, orElseGet, orElseThrow, ifPresent. Don't use it for fields, parameters or collections.

Interview questions

  • Difference between intermediate and terminal operations?
  • Difference between map and flatMap?
  • How would you find the second highest salary with streams?
  • Why shouldn't Optional be used as a field or parameter?

Immutable classes & records

An immutable object's state never changes after construction. Records (Java 16) make immutable data carriers one line long.

  • Recipe: make the class final, all fields private final, no setters, initialise everything in the constructor, and defensively copy mutable inputs and outputs.
  • Benefits: thread-safe without locks, safe to share and cache, safe as map keys, easier to reason about.
  • A record record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors x()/y(), and equals, hashCode, toString.
  • Records are implicitly final, cannot extend another class (they extend java.lang.Record), but can implement interfaces and add methods and static members.
  • Use a compact constructor for validation and normalisation. Records are only shallowly immutable: a List component must be copied (List.copyOf).
  • Modifying an immutable object means returning a new one (withX, plus), like String and LocalDate.

Interview questions

  • How do you create an immutable class in Java?
  • What is a record and what does it generate?
  • Can a record have extra fields, methods or inheritance?

Sealed classes & pattern matching (instanceof, switch, records)

Sealed types close a hierarchy; pattern matching lets switch check every subtype safely without casts.

  • sealed interface Shape permits Circle, Square lists every allowed subtype (Java 17). Each subtype must be final, sealed or non-sealed.
  • Pattern matching for instanceof (Java 16): if (o instanceof String s && s.length() > 3) tests, casts and binds in one step.
  • Switch expressions (Java 14) use ->, return a value, have no fall-through, and use yield in block bodies.
  • Pattern matching for switch (Java 21) allows type patterns, when guards and case null. Over a sealed type the compiler checks exhaustiveness, so no default is needed.
  • Record patterns (Java 21) destructure records inline: case Rect(double w, double h) -> w * h. They can be nested.
  • Together these give algebraic data types: add a new subtype and every non-exhaustive switch fails to compile.

Interview questions

  • What are sealed classes and why use them?
  • What does pattern matching for switch add over the old switch?
  • Switch statement vs switch expression?

var, text blocks & what's new in Java 21 (and 25)

Small syntax wins since Java 10, plus the Java 21 LTS headline features.

  • var (Java 10) infers the type of local variables from the initializer. It is still static typing. Not allowed for fields, method parameters or return types, and needs an initializer.
  • Text blocks (Java 15): """ multi-line strings. The common leading indentation is stripped based on the least-indented line, including the closing delimiter.
  • Java 21 LTS (Sept 2023): virtual threads, sequenced collections, record patterns, pattern matching for switch, generational ZGC (opt-in).
  • Sequenced collections add getFirst, getLast, addFirst, addLast, removeFirst, reversed to lists, deques, LinkedHashSet, LinkedHashMap and sorted sets and maps.
  • Virtual threads are cheap JVM-managed threads for blocking I/O code (Executors.newVirtualThreadPerTaskExecutor()). Details are on the Java Multithreading page.
  • Java 25 LTS (Sept 2025) finalised compact source files with instance main methods, flexible constructor bodies (statements before super(...)), module import declarations and scoped values.

Interview questions

  • Is var dynamic typing?
  • What are the key features of Java 21?
  • Why do companies stay on LTS versions?

JVM internals

JVM memory (heap, stack, metaspace) & garbage collection

Objects live on the GC-managed heap, method frames on per-thread stacks, and class metadata in native metaspace.

  • Heap (shared): all objects and arrays. Divided into young (eden + survivor spaces) and old generations. Sized with -Xms / -Xmx. Full → OutOfMemoryError: Java heap space.
  • Stack (one per thread): a frame per method call with local variables, operand stack and return address. Primitives and references live here. Too deep → StackOverflowError. Sized with -Xss.
  • Metaspace (Java 8+, native memory): class metadata. Replaced PermGen. Unbounded by default; cap with -XX:MaxMetaspaceSize. Class-loader leaks cause OutOfMemoryError: Metaspace.
  • Others: PC register per thread, native method stacks, code cache (JIT output), direct buffers.
  • GC basics: an object is garbage when it is unreachable from GC roots (thread stacks, static fields, JNI refs). Cycles are collected too. Most objects die young (generational hypothesis), so young GCs are frequent and cheap.
  • G1 (default since Java 9): region-based, collects regions with the most garbage first, aims for a pause target (-XX:MaxGCPauseMillis, default 200 ms). ZGC: concurrent, sub-millisecond pauses, huge heaps; generational since Java 21 and the only mode since Java 24.

Interview questions

  • What is stored on the heap vs the stack?
  • Why was PermGen replaced by Metaspace?
  • How does the GC decide an object is garbage?
  • G1 vs ZGC: when would you choose each?

Class loading, reflection & serialization

Class loaders find and define classes using parent-first delegation; reflection and serialization work on classes at runtime.

  • Built-in loaders: Bootstrap (core java.base, written in native code, shown as null), Platform (other JDK modules; was the Extension loader before Java 9), Application/System (your classpath).
  • Parent delegation: a loader asks its parent first and only loads the class itself if the parent can't. This stops apps from replacing java.lang.String.
  • Lifecycle: Loading → Linking (verify, prepare static fields with defaults, resolve symbols) → Initialization (run static initializers) — lazily, on first active use.
  • A class is identified by its name and its defining loader. The same class loaded by two loaders gives two types, and casting between them throws ClassCastException.
  • Reflection (Class, Field, Method, Constructor) inspects and calls members at runtime. Frameworks (Spring, Hibernate, Jackson, JUnit) rely on it. It is slower, skips compile-time checks, and since Java 17 cannot open JDK internals unless you use --add-opens.
  • Serialization: a class implements Serializable; transient and static fields are skipped; declare serialVersionUID. Deserialization does not run the class's constructors and is a known security risk, so prefer JSON/Protobuf and use deserialization filters.

Interview questions

  • Explain the class loader delegation model.
  • What triggers class initialization?
  • What is serialVersionUID and what happens if you don't declare it?
  • What are the downsides of reflection?