LearnThatStack Ace your next interview

Java

Assumes Java 21. Features after Java 8 name their version Checked Nov 2026 83 code snippets

The model

  • A primitive variable holds its value. A reference variable points to a heap object, so b = a copies the reference, not the object.
  • Java always passes by value. A method gets a copy of the reference, so it can change a shared object but not the caller's variable.
  • == compares references. equals() compares content, and equal objects must return the same hashCode().
  • The JVM runs the bytecode from javac, compiles hot methods with the JIT, and frees unreachable objects with garbage collection.
  • Threads share one heap, so shared writes need synchronization.
abPoint(1,2)
Same objectStack variables a and b hold one reference to the heap object, so a == b is true.
acPoint(1,2)Point(1,2)
Equal objectsSame content, two objects. a == c is false, and a.equals(c) can be true.
listcopyold listnew list
Method callA parameter starts as a copy of the reference. Reassigning it moves only the copy.

Types & equality

what a variable holds and what == compares

Classes & inheritance

how classes share code and hide it

Access, static and super

Allow only the classprivate
Allow the packageNo modifier, package-private.
Also allow subclassesprotected
Allow all codepublic
Keep one shared copystatic int count;
Call the parentsuper(name);super.save();

TipA top-level class can only be public or package-private.

TrapA static method has no this, so it can't use instance fields directly.

The four pillars of OOP

Hide the internalsEncapsulation
Extend a classInheritance
Vary a call by typePolymorphism
Expose only essentialsAbstraction

Overload, override, hide

Reuse a name with new parametersOverloading. The compiler picks.
Replace an inherited method@Override. The object's class picks at runtime.
Redeclare a static methodHiding. The declared type picks.

TrapA different return type alone isn't an overload. Static, private and final methods can't be overridden.

Abstract class, interface, composition

Share state across related classesabstract class A
Give unrelated classes a capabilityinterface Flyable
Implement many typesimplements A, B
Reuse by delegatingprivate Engine e;
Say who owns the partAssociation owns nothing. Aggregation holds it. Composition owns it.

TipPrefer composition. A change in a parent can break every subclass.

TrapAn interface holds no instance state, only public static final constants. default methods add behaviour without it.

Collections

pick the structure and know its cost

Pick a collection

Keep orderArrayList, duplicates allowed.
Reject duplicatesHashSet, O(1) on average.
Keep elements sortedTreeSet, O(log n).
Read by indexArrayList is O(1), LinkedList is O(n).
Work at the endsLinkedList is O(1), but ArrayDeque is often faster.

TipMap doesn't extend Collection. The framework has two separate roots.

TrapInserting in the middle of a LinkedList is still O(n), unless an iterator already points there.

Inside HashMap

0123NodeNodeNodeNodeNode
BucketsA bucket holds a list of nodes. Past 8 entries it becomes a red-black tree.
Pick the buckethash & (capacity - 1)
Know when it resizesPast capacity times 0.75, it doubles and rehashes.

TipA bucket only becomes a tree in a table of 64 or more. A smaller table resizes instead.

TrapOverride equals() without hashCode(), and a lookup with an equal key can return null.

Hashtable and ConcurrentHashMap

Read old synchronized codeHashtable locks every method.
Share a map across threadsConcurrentHashMap. Reads take no lock.
Say how it writesCompare-and-swap on an empty bucket. Otherwise it locks the first node.

TipHashMap allows one null key. Hashtable and ConcurrentHashMap reject null.

TrapCheck-then-put isn't atomic, even on a synchronized map. Use computeIfAbsent or merge.

Sort, iterate and update

Set a natural ordercompareTo(T other)
Sort by a keyComparator.comparing(E::name)
Remove while iteratingiter.remove()
Iterate a snapshotCopyOnWriteArrayList
Count wordsmap.merge(w, 1, Integer::sum)
Make an unmodifiable list (9+)List.of(1, 2)

TipKeep natural order consistent with equals(). A TreeSet treats a compare result of 0 as a duplicate.

TrapAdding to an ArrayList in a loop throws ConcurrentModificationException. The check is best-effort.

Exceptions

what you must catch and what gets lost

Threads & locks

share memory without losing updates

JVM, memory & GC

what runs code and frees memory

OutOfMemoryError, leaks, references

Dump the heap on error-XX:+HeapDumpOnOutOfMemoryError
Find what holds memoryA heap dump in Eclipse MAT.
Name common leaksStatic collections, unclosed resources, inner classes, thread locals.
Cache until memory runs lownew SoftReference<>(v)
Drop once only weak references remainnew WeakReference<>(v)

TipA phantom reference's get() always returns null, so it only schedules cleanup.

TrapRaise -Xmx only if the data really needs the space. If it's a leak, fix the reference.

Modern Java

lambdas, streams and what came after Java 8

Lambdas and streams

people.stream()source .filter(p -> p.age() >= 18)intermediate .map(Person::name)intermediate .collect(Collectors.toList());terminal
Pass a functionx -> x * 2
Shorten a lambdaString::toUpperCase
Return a value that may be absentOptional.ofNullable(v)

TipA functional interface has one abstract method, so a lambda can implement it.

TrapIntermediate steps do nothing until the terminal one runs, and a stream can be used only once.

After Java 8

Infer a type (10+)var n = 10;
Switch as a value (14+)case SAT -> "Off";
Test and cast (16+)o instanceof Point p
Limit subclasses (17+)sealed class A permits B
Name the newest LTSJava 25, with scoped values.

Modules, annotations, reflection

Share a packageexports com.app.api;
Keep an annotation for reflection@Retention(RUNTIME)
Call a method found at runtimemethod.invoke(obj)

TipA package a module doesn't export stays hidden, even its public classes.

TrapSince Java 17, setAccessible(true) throws InaccessibleObjectException where a module doesn't open the package.

I/O, JDBC & transactions

files, objects and databases

Spring Boot & microservices

what the framework does

Design patterns & testing

the usual patterns and how to test

Mock with Mockito

Set a mock's answerwhen(s.pay()).thenReturn(true);
Check the callverify(s).pay();

TrapA test that mocks everything only checks that the code calls its mocks.

Found this useful? Pass it on.
Pro · $10/mo

This sheet stays free. With Pro, you can:

  • Every answer on this sheet. Read the full answer to all 95 questions it links, not just the 13 free ones.
  • My sheet. The cards you star and the ones you miss in Quiz me, from every sheet, on one page to quiz and print.
  • PDFs. Download this sheet and My sheet, laid out for A4, with every question a link to its answer.
  • The rest of Pro. Every answer in the question library, and 1,000 AI credits a month.