Cheat Sheets

Three dense quick references by persona—syntax and collections for beginners, streams and concurrency for mid-level, JVM and architecture for senior engineers. Use Copy sheet for plain text, persona filters to focus one level, or print (Cmd/Ctrl+P).

beginner mid senior

Beginner Cheat Sheet

Syntax, primitives, control flow, String API, core Collections, exceptions. Deep dives: Basics, Collections, Exceptions.

beginner

Data types & variables

TypeSizeExample / notes
byte8-bit-128127
short16-bitRare except I/O buffers
int32-bitDefault for integers
long64-bitSuffix L: 1_000_000L
float32-bitSuffix f
double64-bitDefault for decimals
char16-bit UTF-16'A', not a string
booleantrue / false only
var (10+)inferredLocal only; must have initializer
int count = 0;
final String name = "Ada";   // reference final — can't reassign ref
var list = new ArrayList<String>();  // inferred type

Operators & control flow

ConstructSyntaxNotes
if / elseif (x > 0) { } else { }Condition must be boolean
forfor (int i = 0; i < n; i++)Classic index loop
enhanced forfor (var x : list)Iterable / array
whilewhile (cond)Pre-test loop
do-whiledo { } while (cond);Runs at least once
switchswitch (x) { case 1 -> … }Arrow form: no fall-through
break / continueinside loops/switchLabeled break rare
ternarycond ? a : bBoth branches evaluated type-compatible

String methods (high-use)

MethodReturnsUse
length()intChar count (not UTF-8 bytes)
isEmpty() / isBlank()booleanBlank = whitespace only (11+)
equals(s)booleanContent compare; never == for strings
equalsIgnoreCase(s)booleanCase-insensitive
compareTo(s)intSort order; sign = less/greater
substring(b, e)String[begin, end) index
indexOf / lastIndexOfint-1 if missing
contains / startsWith / endsWithbooleanSearch helpers
strip() (11+)StringTrim Unicode whitespace
split(regex)String[]Regex split; limit param for max parts
join(delimiter, parts)StringStatic — join collection/array
formatted / formatString"%s %d".formatted(a, n)
toLowerCase / toUpperCaseStringLocale overload for i18n
// Text blocks (15+)
String sql = """
    SELECT id, name FROM users
    WHERE active = true
    """;

Common Collections

InterfaceImplementationsKey ops
ListArrayList, LinkedListadd, get(i), remove, size
SetHashSet, TreeSetadd, contains — unique elements
MapHashMap, TreeMapput, get, getOrDefault, keySet
QueueArrayDequeoffer, poll — FIFO
List<String> list = new ArrayList<>();
list.add("a");
Map<String, Integer> map = new HashMap<>();
map.put("k", 1);
for (var e : map.entrySet()) {
    String k = e.getKey();
    int v = e.getValue();
}

Exception handling

FormWhen
try { } catch (E e) { }Handle checked or unchecked
finally { }Always runs (except System.exit)
try-with-resourcestry (var in = …) { } — auto-close
throw new E("msg")Signal error
throws EDeclare checked exceptions on method
UncheckedRuntimeException, IllegalArgumentException — no throws required
try (var reader = Files.newBufferedReader(path)) {
    // use reader
} catch (IOException e) {
    throw new UncheckedIOException(e);
}

Mid-Level Cheat Sheet

Streams, Optional, generics wildcards, java.util.concurrent, complexity. Chapters: Functional, Generics, Concurrency.

mid

Stream operations

OpTypeExample
stream()sourcelist.stream(), Arrays.stream(a)
filterintermediate.filter(x -> x > 0)
mapintermediate.map(User::name)
flatMapintermediate.flatMap(u -> u.roles().stream())
distinctintermediateUnique by equals
sortedintermediate.sorted(Comparator.naturalOrder())
limit / skipintermediatePagination-style
takeWhile / dropWhileintermediateOrdered streams (9+)
collectterminal.toList() (16+), Collectors.toSet()
reduceterminal.reduce(0, Integer::sum)
forEachterminalSide effects — avoid in pure pipelines
count / min / maxterminalReductions
findFirst / anyMatchterminal short-circuitStops early when possible
groupingBycollectorCollectors.groupingBy(User::dept)
partitioningBycollectorSplit by predicate → two buckets
toMapcollectorMerge function for duplicate keys
Map<String, List<User>> byDept = users.stream()
    .filter(User::active)
    .collect(Collectors.groupingBy(User::department));

// Parallel — only when data large & ops cheap; watch ordering
long n = list.parallelStream().filter(x -> x > 0).count();

Optional

MethodPurpose
of(v) / ofNullable(v)Present box; nullable safe
empty()Singleton empty
isPresent() / isEmpty()Check (11+ isEmpty)
ifPresent(Consumer)Run if present
orElse(x) / orElseGet(Supplier)Default value
orElseThrow()Fail if empty
map / flatMapTransform without nested Optional
filterEmpty if predicate false
stream() (9+)0 or 1 element stream
// Don't use Optional fields/parameters by default in domain models
String city = Optional.ofNullable(user)
    .flatMap(User::address)
    .map(Address::city)
    .orElse("unknown");

Generics wildcards (PECS)

WildcardMeansProducer / Consumer
<T>Type parameterDefinition site
? extends XUpper bound — read as XProducer — get items out
? super XLower bound — accept XConsumer — put X in
?UnboundedOnly safe via Object
// PECS: Producer Extends, Consumer Super
void copy(List<? extends Number> src, List<? super Integer> dest) {
    for (Number n : src) dest.add(n.intValue());
}

Concurrency utilities

APIUse
synchronizedIntrinsic lock on object
volatileVisibility — not atomic compound ops
ReentrantLockExplicit lock, tryLock, fairness
AtomicInteger etc.Lock-free CAS counters
ConcurrentHashMapThread-safe map — segment/CAS
CopyOnWriteArrayListRead-heavy, rare writes
ExecutorServicesubmit, invokeAll, shutdown
ExecutorsnewFixedThreadPool, newCachedThreadPool
CountDownLatchWait for N events
CyclicBarrierThreads rendezvous
SemaphoreLimit concurrent access
CompletableFutureAsync pipeline — see senior sheet
BlockingQueueArrayBlockingQueue, LinkedBlockingQueue
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<String> f = pool.submit(() -> "ok");
pool.shutdown();
pool.awaitTermination(30, TimeUnit.SECONDS);

Collections — time complexity (average)

Structureget / containsaddremoveNotes
ArrayListO(1) index / O(n) searchO(1)* endO(n)*amortized; insert middle O(n)
LinkedListO(n)O(1) endsO(1) with iteratorPoor cache locality
HashMapO(1)O(1)O(1)Worst O(n) if hash degrade
TreeMapO(log n)O(log n)O(log n)Sorted keys
HashSetO(1)O(1)O(1)Backed by map
TreeSetO(log n)O(log n)O(log n)Sorted set
PriorityQueuepeek O(1)O(log n)O(log n)Heap — not sorted iteration
ConcurrentHashMapO(1)O(1)O(1)Scalable concurrent reads/writes

Senior / Architect Cheat Sheet

JVM flags, GC tuning, JMH, async composition, virtual threads, patterns. Chapters: JVM, Performance, Modern Java, Patterns.

senior

JVM flags (common)

FlagPurpose
-Xms / -XmxInitial / max heap (e.g. -Xmx4g)
-XX:MaxRAMPercentageContainer-aware heap % (CGroup)
-XX:+UseG1GCG1 collector (default on many JDKs)
-XX:MaxGCPauseMillisG1 pause target (hint)
-XX:+UseZGC / UseGenerationalZGCLow-latency ZGC (21+ generational)
-Xlog:gc*Unified GC logging (9+)
-XX:+HeapDumpOnOutOfMemoryErrorDump on OOM
-XX:HeapDumpPath=…Dump file location
-XX:NativeMemoryTrackingNMT summary / detail
-XX:+AlwaysPreTouchTouch heap pages at start (latency vs startup)
-XX:+PrintCompilationLog JIT compiles (with UnlockDiagnosticVMOptions)
-XX:+FlightRecorderEnable JFR
-D…System properties

GC tuning (practical)

SymptomDirection
Frequent long pausesReduce heap pressure; tune pause goal; consider ZGC
High throughput batchG1 or parallel; larger young gen
Container OOMKilledSet -Xmx below cgroup limit; MaxRAMPercentage
Metaspace growthClass loaders / reflection; -XX:MaxMetaspaceSize
Native memory leakNMT, direct buffers, JNI, thread stacks
# JDK 9+ GC log
java -Xlog:gc*:file=gc.log:time,uptime,level -jar app.jar

# JFR short recording
jcmd <pid> JFR.start name=debug settings=profile duration=120s filename=out.jfr

JMH annotations

AnnotationRole
@BenchmarkMeasured method
@WarmupIterations/time before score
@MeasurementRecorded iterations
@ForkSeparate JVM runs
@State(Scope.Thread)Per-thread fixture
@BenchmarkModeThroughput, AverageTime, SampleTime, …
@OutputTimeUnitReport units
Blackhole.consumePrevent dead code elimination
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(1)
public class MyBench {
    @Benchmark
    public void run(Blackhole bh) { bh.consume(work()); }
}

CompletableFuture

MethodPurpose
supplyAsync(Supplier)Async value
runAsync(Runnable)Async void
thenApply / thenAcceptMap / consume result
thenComposeFlat-map nested CF
thenCombineMerge two CFs
allOf / anyOfWait for all / first
exceptionallyRecover from failure
handleSuccess or failure branch
orTimeout / completeOnTimeoutDeadline (9+)
join() / get()Block for result
CompletableFuture<User> user = CompletableFuture
    .supplyAsync(() -> fetchUser(id), executor)
    .thenCompose(u -> enrichAsync(u))
    .orTimeout(2, TimeUnit.SECONDS);

CompletableFuture.allOf(f1, f2).join();

Virtual threads (Java 21+)

APINotes
Thread.startVirtualThread(r)Fire-and-forget virtual thread
Thread.ofVirtual().start(r)Builder: name, factory
Executors.newVirtualThreadPerTaskExecutor()One virtual thread per task
Thread.isVirtual()Check thread kind
Pinnedsynchronized + blocking native can pin carrier
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i ->
        executor.submit(() -> handleRequest(i)));
}

Design patterns — quick reference

PatternProblemJava / Spring hint
SingletonOne instanceEnum; Spring default scope
Factory MethodDefer concrete type@Bean methods
Abstract FactoryRelated product familyProfile-specific config
BuilderMany optional fieldsHttpRequest.newBuilder()
StrategySwap algorithmInject interface
ObserverNotify dependents@EventListener
DecoratorAdd behaviorI/O streams
AdapterLegacy API bridgeWrapper implements port
FacadeSimple API over subsystemService layer
ProxyControl accessSpring AOP, JDK/CGLIB
Template MethodFixed skeletonJdbcTemplate
Chain of ResponsibilityPipeline handlersServlet / Security filters
CommandRequest as objectUndo, job queue
RepositoryPersistence boundarySpring Data JPA
Null ObjectAvoid null checksNOOP implementation

Profiling one-liners

ToolCommand / action
async-profiler./profiler.sh -d 60 -f cpu.html <pid>
Heap dumpjcmd <pid> GC.heap_dump heap.hprof
Thread dumpjcmd <pid> Thread.print
JMCOpen .jfr — Hot Methods, GC, locks