Quick Reference · the JVM language · through Java 21 LTS · expanded edition

java cheat sheet 21 LTS

One language, two steps: javac compiles your .java to portable bytecode, and the JVM runs that same .class on any machine. Learn the object model and the compile-then-run map, and the syntax falls into place — right up to Java 21's records, patterns and virtual threads.

setup & structure types & syntax classes & OOP generics · collections · streams flow · errors · threads modern / new gotcha most common N added in Java N Nᵖ preview in N ✕ 23 later removed

Distilled & cross-checked across: dev.java · docs.oracle.com/javase/21 · openjdk.org (JEPs 430·431·439·440·441·444·445·453) · InfoQ · Baeldung · Happy Coders — every feature compiled & run on OpenJDK 21.

From source to running program — and why it runs anywhere
COMPILE ONCE, THEN RUN ON THE JVM Hello.java source you write javac Hello.class bytecode · portable java the JVM (HotSpot) classloader bytecodeverifier interpreter+ JIT (C1/C2) GC · heapmemory running program WRITE ONCE, RUN ANYWHERE — ONE .class, MANY JVMs Hello.class same bytecode everywhere Windows JVMx64 machine code macOS JVMARM machine code Linux JVMx64 machine code
// Hello.java — compile: javac Hello.java  ·  run: java Hello
record Point(int x, int y) {}                 // immutable data (16)

void greet(Object o) {                        // pattern-matching switch (21)
    String msg = switch (o) {
        case Point(var x, var y) -> "at " + x + "," + y;
        case String s            -> "hi " + s;
        case null                -> "nobody";
        default                  -> "?";
    };
    System.out.println(msg);
}

try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {  // 21
    for (var name : List.of("ada", "linus")) pool.submit(() -> greet(name));
}

Modern Java · 8 → 21

Java ships every 6 months; the LTS releases (violet) are the ones teams run in production. Here's the road to 21.

Java 8 2014 · LTSlambdas · streams · Optional · java.time
9–10 2017–18modules · List.of · var
Java 11 2018 · LTSHttpClient · String methods · run .java
14–16 2020–21switch expr · text blocks · records
Java 17 2021 · LTSsealed classes · pattern-matching groundwork
Java 21 2023 · LTSvirtual threads · patterns · sequenced coll.
Virtual Threads21
Executors.newVirtualThreadPerTaskExecutor()

Millions of cheap threads. Blocking I/O code scales like async — the JVM unmounts a blocked virtual thread off its OS carrier.

Pattern Matching · switch21
case Shape s when s.big() -> ...

Switch on an object's type, bind it, and guard with when — no cast, no fall-through.

Record Patterns21
case Point(int x, int y) -> x + y

Deconstruct a record straight into its components inside instanceof and switch; nests deeply.

Sequenced Collections21
list.getFirst() · getLast() · reversed()

One interface (SequencedCollection / …Map) gives every ordered collection uniform ends and a reversed view.

Sealed + exhaustive switch17→21
sealed interface Shape permits

Sealed types (17) close a hierarchy; the pattern switch (21) then needs no default — the compiler proves it total.

Preview in 2121ᴾ
STR.0 · void main() · _

String templates (later withdrawn in 23), instance main, unnamed _ vars, scoped values & structured concurrency — all preview.

01Setup & Runjavac · java
02Program Anatomythe skeleton
03Primitives & Literals8 built-in value types
04Variables & varnames & inference
05Operatorsarithmetic & logic
06Stringsimmutable text
07Numbers & Mathparse · box · compute
08Arraysfixed-size sequences
09Control Flowbranch & loop
10Switchstatement → expression → pattern
11Classes & Objectsthe building block
12Inheritanceextend & override
13Interfacesa contract of behavior
14Recordstransparent data carriers
15Enums & Sealedclosed sets of types
16Genericstype-safe containers
17Collectionslists, sets, maps
18Comparing & Sortingnatural & custom order
19Lambdas & Method Refsfunctions as values
20Streamslazy data pipelines
21Exceptionsfail loudly, recover well
22Dates & Timejava.time
23Console & Files I/Oin, out, disk
24Concurrencythreads, old & new

Six ideas worth a picture

The mental models behind the syntax — memory, errors, sealed exhaustiveness, the Java 21 threading model, the collections family, and how a stream actually runs.

values vs references

Primitives hold a value; object variables hold a pointer — so two names can share one heap object.

STACK HEAP int n =5 primitive → holds the value List a ● List b ● [1, 2, 3] one object a and b share it → a.add() shows in b

checked vs unchecked

Everything descends from Throwable. RuntimeException is unchecked; other exceptions must be caught or declared.

Throwable Error don't catch (OOM…) Exception RuntimeExceptionUNCHECKED IOExceptionCHECKED … NPE · ClassCast · IllegalArgument unchecked = compiler doesn't force handling must catch or declare

sealed + exhaustive switch

A sealed type lists its subtypes, so a pattern switch that covers them needs no default.

sealed Shape Circle Square Triangle switch (shape) { case Circle c -> … case Square s -> … case Triangle t -> … // no default! compiler proves it is total

virtual vs platform threads

Many virtual threads mount onto a few OS threads; a blocked one unmounts, freeing its carrier.

virtual threads (millions, cheap) mount ▼ · blocked I/O ⇒ unmount ▲ carrier / platform threads (a handful) OS T1OS T2OS T3 operating-system scheduler

the collections family

Collection branches into List, Set and Queue; Map is a separate key→value hierarchy.

Collection<E> List Set Queue / Deque ArrayListLinkedList HashSetTreeSet ArrayDeque Map<K,V> HashMapTreeMapLinkedHashMap not a Collection List = ordered · Set = unique · Queue = ends · Map = key→value pick the interface for the guarantee, the class for the performance

how a stream runs

Intermediate ops (filter/map) are lazy; the single terminal op is what actually pulls data through.

SOURCE list.stream() INTERMEDIATE · lazy .filter(...).map(...).sorted(...) TERMINAL · eager .collect(...) → result / value filter & map only build a recipe — the terminal op runs it, once no terminal op ⇒ nothing executes

Worth memorizing

== vs .equals()== compares references; .equals() compares values
Integer cacheautoboxed −128..127 are shared, so == may lie above 127
int / int5/2 == 2 — cast one side to double for real division
String immutableevery edit makes a new object; use StringBuilder in loops
checked vs uncheckedRuntimeExceptions are free; others must be caught or declared
arrays covariantObject[] a = strings; a[0]=1 → ArrayStoreException at runtime
generics erasedno new T[], no x instanceof List<String>
getFirst() throwssequenced ends throw on empty — they are not Optional
string templatesSTR."…" was preview in 21/22, removed in 23 — don't ship it
var is local-onlynot for fields, params, returns, or var x = null
switch arrow-> cases never fall through; no break needed
float default3.14 is a double; write 3.14f / 100L for float / long
catch ordersubclasses before superclasses, else "already caught"
finally winsa return in finally swallows exceptions — avoid it
parse throwsInteger.parseInt("x") throws NumberFormatException — validate first
double ≠ money0.1 + 0.2 != 0.3 — use new BigDecimal("0.1") for currency
java.time is immutabled.plusDays(1) returns a new date; the original is unchanged
Scanner newlinenextInt() leaves the \n behind — a stray nextLine() reads empty
streams are lazyfilter/map do nothing until a terminal op like toList() runs
Comparator nullscomparing on a null key throws — wrap with Comparator.nullsFirst