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
- JDK = JRE + dev tools (
javac,jar,jshell). JRE = JVM + class library. JVM runs bytecode, with an interpreter plus JIT (C1/C2). - 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.
Integercaches -128 to 127:Integer a = 127, b = 127; a == bis true, but for 128 it is false. Always compare wrappers withequals.- Strings are immutable and literals live in the String pool (on the heap since Java 7).
new String("x")makes a new object. UseStringBuilderin loops. - If you override
equals, you must overridehashCode. Equal objects must have equal hash codes, or hash-based collections break. - Interfaces can have
defaultandstaticmethods (Java 8) andprivatemethods (Java 9). Abstract classes can have state and constructors; interfaces cannot have instance fields. - Checked exceptions (
IOException) must be caught or declared; unchecked ones extendRuntimeException. try-with-resources closes in reverse order and keeps close errors as suppressed. - A
returninfinallyoverrides thetryreturn and swallows exceptions.finallydoes not run afterSystem.exit. - Generics are erased at runtime. PECS: Producer
extends, Consumersuper.List<Integer>is not aList<Number>. 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).ArrayList= resizable array (O(1) get, grows 1.5x).LinkedList= doubly linked list; rarely faster in practice. UseArrayDequefor stacks and queues.- Fail-fast iterators (
ArrayList,HashMap) throwConcurrentModificationException; fail-safe / weakly consistent ones (CopyOnWriteArrayList,ConcurrentHashMap) do not. - Streams are lazy, single-use and need a terminal operation.
Optionalis for return values, not fields or parameters. - Records (16), sealed classes (17), pattern matching for
instanceof(16) andswitch(21), text blocks (15),var(10). Java 21 and Java 25 are the current LTS releases. - 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.
- 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,jcmdandjfr. - 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 = nullon 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 convertsint→IntegerviaInteger.valueOf; unboxing callsintValue(). Integer.valueOfreturns cached objects for -128..127 (the JLS requires it).Byte,Short,LongandCharacter(0..127) cache too;FloatandDoubledo not.- Unboxing a
nullwrapper throws NullPointerException. This often hides inmap.get(key)assigned to anint. - Integer overflow wraps silently:
Integer.MAX_VALUE + 1isInteger.MIN_VALUE. UseMath.addExactto get an exception instead. float/doubleare binary floating point. UseBigDecimal(built from a String) for money.
Interview questions
- Why is
Integer a = 127, b = 127; a == btrue but false for 128? - What is autoboxing and what can go wrong?
- Why use
BigDecimalfor money?
String immutability, the String pool & StringBuilder
Strings never change. Literals are shared through the pool. Build strings in loops with StringBuilder.
Stringis final and immutable. Methods likeconcat,replaceandtoUpperCasereturn a new String.- Why immutable: safe to share and cache (the pool), thread-safe, safe as
HashMapkeys (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 callintern(). ==compares references;equalscompares characters. Always useequals(or"lit".equals(x)to be null-safe).StringBuilderis mutable and not synchronized (fast).StringBufferis 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 aninvokedynamiccall instead of a fixedStringBuilderchain.
Interview questions
- Why is String immutable in Java?
- How many objects does
String s = new String("hello")create? - What is the difference between
==andequalsfor 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
thisand 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 finalprimitives 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
finalmake 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:
extendsone class (single inheritance of state),implementsmany 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 arepublic abstractunless markeddefault,staticorprivate. 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.equalsis identity (==). Override it for value objects. equalsmust be reflexive, symmetric, transitive, consistent, andx.equals(null)must be false.- hashCode rule: if
a.equals(b)thena.hashCode() == b.hashCode(). The reverse is not required (collisions are allowed). - Hash collections first find the bucket by
hashCode, then checkequals. WronghashCodemeans the search looks in the wrong bucket. - Use the same fields in both methods, prefer immutable fields, and use
Objects.equals/Objects.hashor let a record generate them. instanceofvsgetClass()in equals:getClass()keeps symmetry with subclasses;instanceofis 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 likeOutOfMemoryError, don't catch) andException.RuntimeExceptionand 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
AutoCloseableautomatically, in reverse order, even when the body throws. Close failures are attached as suppressed exceptions. finallyalways runs after try/catch, except onSystem.exit, a JVM crash or a killed thread. Areturnorthrowin 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,finallyandfinalize? - 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
Twith its bound (Objector e.g.Comparable) and inserts casts.List<String>andList<Integer>share oneClassat runtime. - Because of erasure you cannot do
new T(),new T[],instanceof List<String>, use primitives as type arguments, or overloadm(List<String>)withm(List<Integer>). - Generics are invariant:
List<Integer>is not aList<Number>. Arrays are covariant (Integer[]is anObject[]) and fail at runtime withArrayStoreException. - PECS: Producer
extends, Consumersuper. Read fromList<? extends Number>; write toList<? 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).Mapis 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. HashSetis aHashMapwith dummy values.LinkedHashSet/LinkedHashMapkeep insertion order.TreeSet/TreeMapare red-black trees, sorted, O(log n).ArrayDequeis the recommended stack and queue (faster thanStackandLinkedList).PriorityQueueis a binary heap:pollreturns the smallest item.List.of,Set.of,Map.of(Java 9) are immutable and reject nulls.Arrays.asListis fixed-size but allowsset.
Interview questions
- ArrayList vs LinkedList: which do you use and why?
- Difference between HashSet, LinkedHashSet and TreeSet?
- How does
HashSetensure 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): computeh = k.hashCode(), spread it withh ^ (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
ior moves toi + 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
nullkey is allowed (always bucket 0).HashMapis not thread-safe; useConcurrentHashMapfor 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 amodCount. If the collection changed structurally outside the iterator, the nextnext()throwsConcurrentModificationException. 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.
CopyOnWriteArrayListiterates a snapshot;ConcurrentHashMapiterates 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
nullkeys and values, becausegetreturning 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).
@FunctionalInterfacemakes 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 likeIntPredicate. - Lambdas can capture local variables only if they are effectively final. They have no own
this;thismeans 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.mapis one-to-one;flatMapturns each element into a stream and flattens them. Java 16 addedstream.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
mapandflatMap? - 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 fieldsprivate 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, accessorsx()/y(), andequals,hashCode,toString. - Records are implicitly
final, cannot extend another class (they extendjava.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
Listcomponent must be copied (List.copyOf). - Modifying an immutable object means returning a new one (
withX,plus), likeStringandLocalDate.
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, Squarelists every allowed subtype (Java 17). Each subtype must befinal,sealedornon-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 useyieldin block bodies. - Pattern matching for switch (Java 21) allows type patterns,
whenguards andcase null. Over a sealed type the compiler checks exhaustiveness, so nodefaultis 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,reversedto lists, deques,LinkedHashSet,LinkedHashMapand 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
mainmethods, flexible constructor bodies (statements beforesuper(...)), module import declarations and scoped values.
Interview questions
- Is
vardynamic 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 causeOutOfMemoryError: 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 asnull), 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;transientandstaticfields are skipped; declareserialVersionUID. 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
serialVersionUIDand what happens if you don't declare it? - What are the downsides of reflection?