Cheatsheets
Java
Classes, generics, collections, streams & lambdas, records, and exceptions.
Test yourself66 entries
Classes & objects7
class Point { int x, y; }Class declaration with fields.
new Point()Instantiate — allocates on the heap, returns a reference.
this.x = x;Refer to the current instance (disambiguate field vs param).
static int count;Class-level member — one copy shared by all instances.
final int MAX = 10;Assign-once: a final field/variable cannot be reassigned.
Point(int x, int y) { this.x = x; this.y = y; }Constructor — same name as the class, no return type.
a == b vs a.equals(b)Identity vs equality — `==` compares references, `.equals()` compares content.
Access modifiers & keywords8
publicVisible everywhere.
privateVisible only inside the same class.
protectedVisible to the same package and subclasses.
(no modifier)Package-private — the default; visible within the same package only.
abstract class ShapeCannot be instantiated; may have abstract methods to implement.
final class StringCannot be subclassed; `final` on a method blocks overriding.
static { ... }Static initializer block — runs once when the class loads.
private final int id;The default-secure field combo: private (encapsulated) + final (immutable).
Interfaces & inheritance7
interface Drawable { void draw(); }Pure contract — implemented by classes.
class Circle implements DrawableA class implements one or more interfaces.
class Dog extends AnimalSingle-class inheritance (`extends` one class).
super.method()Invoke the parent's version of an overridden method.
@FunctionalInterfaceMarks an interface with exactly one abstract method (a lambda target).
interface A extends B, CAn interface may extend multiple interfaces.
default String name() { return "?"; }Default method — an interface method WITH a body (added in Java 8).
Records, sealed & enums5
enum Day { MON, TUE, WED }Fixed set of named constants — type-safe and switch-friendly.
Day.MON.ordinal()Zero-based position; `.name()` gives the String; `.values()` lists all.
enum Op { ADD { int eval()... } }Enum constants can have bodies and abstract methods (constant-specific behaviour).
record Point(int x, int y) {}Immutable data carrier (Java 16+) — auto fields, ctor, accessors, equals/hashCode/toString.
sealed interface Shape permits Circle, Square {}Restrict who can implement/extend (Java 17+) — a closed, exhaustive type hierarchy.
Generics7
List<String>Parameterised type — element type checked at compile time.
<T> T first(List<T> xs)Generic method — `T` inferred from the argument.
Map<K, V>Multiple type parameters.
var box = new Box<>();Diamond `<>` — the compiler infers the type arguments.
class Box<T> { T value; }Generic class — write the logic once, reuse for any element type with full type safety.
List<? extends Number> / List<? super Integer>Wildcards — bounded variance for read-only (`extends`) vs write (`super`) APIs.
<T extends Comparable<T>>Bounded type parameter — `T` must implement an interface.
Collections7
List<String> l = new ArrayList<>();Ordered, indexed, allows duplicates — array-backed.
Set<String> s = new HashSet<>();No duplicates, no order; `LinkedHashSet` keeps insertion order.
Map<String,Integer> m = new HashMap<>();Key→value pairs, unique keys, O(1) average lookup.
Deque<Integer> dq = new ArrayDeque<>();Double-ended queue — use as a stack/queue (prefer over `Stack`).
List.of(1, 2, 3)Immutable list literal (Java 9+); `Map.of`, `Set.of` too. Throws on mutation.
ArrayList vs LinkedListPick the right List: ArrayList for random access, LinkedList only for heavy ends-insertion.
map.computeIfAbsent(key, k -> new ArrayList<>()).add(v)Build a multimap / counter in one idiomatic line — no get-null-check-put dance.
Streams & lambdas (8+)8
(a, b) -> a + bLambda — anonymous implementation of a functional interface.
String::toUpperCaseMethod reference — shorthand for a lambda that just calls a method.
list.forEach(System.out::println)Iterate with a consumer.
.filter(x -> x > 0)Keep elements matching a predicate (intermediate, lazy).
.map(String::length)Transform each element (intermediate, lazy).
.collect(Collectors.toList())Terminal — materialise the stream into a List (or `.toList()` in 16+).
list.stream().filter(...).map(...).collect(...)The stream pipeline: a lazy, declarative sequence of transforms ending in one terminal op.
Collectors.groupingBy(Fn, downstream)SQL-style GROUP BY for streams — bucket elements, then aggregate each bucket.
Optional, exceptions & var8
Optional<User> findUser(id)A box that may or may not hold a value — encodes 'maybe absent' in the type.
opt.orElse(fallback)Unwrap with a default; `.orElseThrow()`, `.map()`, `.ifPresent()` too.
var list = new ArrayList<String>();Local-variable type inference (Java 10+) — only for locals with an initializer.
throw new IllegalStateException(msg)Raise an exception explicitly.
finally { ... }Always runs (cleanup), whether or not an exception was thrown.
Optional<T> (return type, never a field/param)Replace null returns with Optional so callers must consciously handle 'absent'.
try (var in = Files.newInputStream(p)) { ... }try-with-resources — auto-closes any AutoCloseable, even on exception.
checked vs unchecked exceptionsChecked = compiler-enforced recovery; unchecked (RuntimeException) = programmer bug.
Concurrency & modern idioms9
Runnable r = () -> doWork();A task with no result; `Callable<T>` returns a value/throws.
new Thread(r).start();Low-level thread — prefer an ExecutorService for real work.
synchronized (lock) { ... }Mutual exclusion on a monitor — only one thread at a time.
volatile boolean running;Guarantees visibility of writes across threads (not atomicity).
var n = new AtomicInteger();Lock-free atomic counter — `incrementAndGet()` is thread-safe.
var map = new ConcurrentHashMap<>();Thread-safe map without locking the whole structure.
var pool = Executors.newFixedThreadPool(4)Submit tasks to a managed thread pool instead of spawning raw Threads.
Executors.newVirtualThreadPerTaskExecutor()Virtual threads (Java 21 LTS) — millions of cheap threads for blocking IO.
switch with pattern matching (21+)Modern switch: arrow labels, exhaustiveness, type patterns, and record deconstruction.