Course Java
Java Cheatsheet
Printable quick reference for Modern Java (JDK 17/21): primitive types, String Pool, OOP, inheritance, interfaces, Collections & Generics, exceptions, Stream API, Records, Optional, and concurrency. Print or save as PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
0. Golden rules & common Java pitfalls
Six rules that prevent bugs with strings, references, collections, null, and Streams.
- Always compare String and object contents with .equals() (or Objects.equals(a, b) if nullable), never with ==.
- Java passes references by value: a method can mutate the target object, but reassigning the local parameter never changes the caller variable.
- Dividing two ints (e.g., 5 / 2) truncates toward zero (2): cast at least one operand to double ((double) 5 / 2).
- Generic collections (ArrayList, HashMap) require reference/wrapper types (Integer, Double), never primitives (int, double).
- Never call .remove() directly on a collection inside a for-each loop: it throws ConcurrentModificationException (use Iterator or removeIf).
- A Stream is lazy and single-use: without a terminal operation (collect, sum, findFirst) nothing runs, and reusing a consumed stream throws IllegalStateException.
1. Variables, Primitives, Wrappers & var
Primitives, final & var
final double TAX_RATE = 0.22; int age = 25; long population = 60_000_000L; boolean isActive = true; char grade = 'A'; var message = "Hello Java"; // inferred as StringJava is statically typed: var infers the compile-time type strictly for initialized local variables.
Pitfall: Method-local variables receive no default values: reading them before initialization fails compilation.
Casting, Division & Wrappers
double avg = (double) 5 / 2; // 2.5 (instead of int 2) int num = Integer.parseInt("42"); // 42 String s = String.valueOf(123); // "123" Integer boxed = Integer.valueOf(10);Use Integer.parseInt / Double.parseDouble to convert text into primitive numbers.
Pitfall: Casting (int) 9.8 truncates toward zero without rounding; comparing Integer values > 127 with == can return false due to [-128, 127] caching.
2. Strings, String Pool, StringBuilder & Arrays
String Pool vs new String & StringBuilder
String s1 = "Java"; String s2 = "Java"; // same String Pool slot (s1 == s2 is true) String s3 = new String("Java"); // distinct Heap instance (s1 == s3 is false) boolean eq = s1.equals(s3); // true (content check) StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.append(i).append("-"); } String out = sb.toString(); // "0-1-2-"String is immutable: accumulate text inside loops with StringBuilder to avoid O(N²) Heap allocations.
Pitfall: Operator precedence matters: "Sum: " + 2 + 3 produces "Sum: 23" unless parenthesized as (2 + 3).
Fixed-size Arrays & Arrays Utility
import java.util.Arrays; int[] scores = { 90, 75, 88 }; int[] copy = Arrays.copyOf(scores, scores.length); Arrays.sort(copy); System.out.println(Arrays.toString(copy)); // [75, 88, 90]Use copy.length (field, no parentheses) on arrays and list.size() on collections.
Pitfall: Printing an array directly prints [I@... identity text instead of elements; use Arrays.toString(scores).
3. Control Flow & Switch Expressions
Conditional Branching & Switch Expression (Java 14+)
String badge = switch (role) { case "ADMIN", "OWNER" -> "Full access"; case "EDITOR" -> "Write access"; default -> { yield "Read only"; } };Arrow labels (->) in switch expressions prevent fall-through and enforce compiler-checked exhaustiveness.
Pitfall: Traditional colon labels (case "A":) silently fall through into subsequent cases if break; is omitted.
for, Enhanced for-each & while Loops
for (int i = 0; i < 5; i++) { if (i == 2) continue; System.out.println(i); } for (String item : items) { System.out.println(item); }Prefer enhanced for-each loops whenever numeric indexes are not required.
Pitfall: Java conditions require a strict boolean expression (unlike C or JS truthy/falsy numbers).
4. Classes, Constructors, Encapsulation & Enums
Encapsulated Class & Constructor Overloading
class BankAccount { private final String owner; private double balance; public BankAccount(String owner, double initialBalance) { if (initialBalance < 0) throw new IllegalArgumentException("Negative balance"); this.owner = owner; this.balance = initialBalance; } public BankAccount(String owner) { this(owner, 0.0); // delegates to primary constructor } public double getBalance() { return balance; } }Delegate secondary constructors with this(...) as the first statement to centralize invariants.
Pitfall: Defining any parameterized constructor stops Java from generating the zero-argument default constructor.
Rich Enums & static final Constants
enum Status { PENDING(1), DONE(2); private final int code; Status(int code) { this.code = code; } public int getCode() { return code; } }Java enums are full singleton classes supporting final fields, private constructors, and methods.
Pitfall: Enum constants can safely be compared using ==, which is both null-safe and compile-time type-checked.
5. Inheritance, Interfaces & Sealed Types
extends, super & @Override
abstract class Shape { abstract double area(); } class Circle extends Shape { private final double radius; Circle(double radius) { this.radius = radius; } @Override double area() { return Math.PI * radius * radius; } }Always annotate overridden methods with @Override so signature mismatches fail at compile time.
Pitfall: super(...) must always be the very first statement inside the subclass constructor.
Interfaces, Default Methods & Sealed Hierarchy (Java 17+)
interface Auditable { String auditId(); default String summary() { return "ID:" + auditId(); } } sealed interface Payment permits CardPayment, BankTransfer {} final class CardPayment implements Payment {} final class BankTransfer implements Payment {}sealed hierarchies declare the complete set of permitted subtypes so pattern switches remain exhaustive.
Pitfall: Interface methods implemented on a class must keep explicit public visibility.
6. Collections Framework & Generics
Mutable & Unmodifiable List, Set & Map
import java.util.*; List<String> list = new ArrayList<>(List.of("Java", "Go")); list.add("Rust"); Set<String> unique = new HashSet<>(list); Map<String, Integer> scores = new HashMap<>(); scores.put("Alice", 95); scores.merge("Alice", 5, Integer::sum); // 100 int bob = scores.getOrDefault("Bob", 0);List.of(...) yields unmodifiable lists rejecting nulls; Map.merge cleanly simplifies counter accumulation.
Pitfall: On ArrayList<Integer>, list.remove(1) removes index 1 rather than value Integer.valueOf(1).
Generic Methods & Bounded Wildcards
public static <T extends Comparable<T>> T maxOf(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } static double sumNumbers(List<? extends Number> values) { return values.stream().mapToDouble(Number::doubleValue).sum(); }Follow PECS: Producer Extends (? extends T) for reading, Consumer Super (? super T) for writing.
Pitfall: Because of Generic Type Erasure, you cannot instantiate new T[] or check obj instanceof List<String>.
7. Exceptions & try-with-resources
try / multi-catch & Exception Chaining
try { int parsed = Integer.parseInt(input); process(parsed); } catch (NumberFormatException | IllegalArgumentException e) { throw new IllegalStateException("Invalid input: " + input, e); }Always chain the original cause exception e when wrapping into a higher-level exception.
Pitfall: Catch specific subclasses before general Exception; never swallow errors inside an empty catch block.
Deterministic try-with-resources (AutoCloseable)
try (var reader = java.nio.file.Files.newBufferedReader(path)) { String firstLine = reader.readLine(); System.out.println(firstLine); } // reader.close() runs automatically even on exceptionAny AutoCloseable resource declared in try(...) is deterministically closed in reverse order upon exit.
Pitfall: Avoid manually closing resources inside finally when try-with-resources already owns their lifecycle.
8. Lambdas, Method References & Stream API
Functional Interfaces & Lambdas
Predicate<String> nonEmpty = s -> !s.isBlank(); Function<String, Integer> lengthFn = String::length; names.removeIf(s -> s.startsWith("_"));Captured local variables used inside a lambda must be final or effectively final.
Pitfall: Mutating shared external collections inside .forEach() or .map() creates race conditions and side-effect bugs.
Lazy Pipeline, flatMap & Collectors
List<String> tags = orders.stream() .filter(o -> o.amount() >= 50) .flatMap(o -> o.tags().stream()) .map(String::toUpperCase) .distinct() .toList(); Map<Integer, Long> countByLen = words.stream() .collect(Collectors.groupingBy(String::length, Collectors.counting()));Streams process elements vertically stage-by-stage and support short-circuiting via findFirst or anyMatch.
Pitfall: Stream.toList() (Java 16+) produces an unmodifiable list that disallows null elements.
9. Records, Optional & Pattern Matching
Immutable Record with Compact Constructor (Java 16+)
public record Order(String id, double total) { public Order { if (id == null || id.isBlank()) throw new IllegalArgumentException("Empty id"); if (total < 0) throw new IllegalArgumentException("Negative total"); } }Records auto-generate private final fields, accessors (id(), total()), equals, hashCode, and toString.
Pitfall: Records are implicitly final and cannot extend abstract base classes (though they can implement interfaces).
Null-Safe Optional & Pattern Matching for instanceof
String city = findUser(id) .map(User::address) .map(Address::city) .orElseGet(() -> fallbackCity()); if (shape instanceof Circle c && c.radius() > 0) { System.out.println(c.area()); }Prefer .orElseGet(supplier) over .orElse(...) when constructing fallbacks so unused calls are skipped.
Pitfall: Never call optional.get() unconditionally without presence checks, and avoid Optional for fields or parameters.
10. Concurrency, NIO.2 Files & JUnit 5
ExecutorService & CompletableFuture
try (ExecutorService pool = Executors.newFixedThreadPool(4)) { CompletableFuture<String> job = CompletableFuture .supplyAsync(() -> "payload", pool) .thenApply(String::toUpperCase); System.out.println(job.join()); }Since Java 19, ExecutorService implements AutoCloseable so try-with-resources handles orderly pool shutdown.
Pitfall: Never share raw HashMap or unsynchronized int++ across threads; use ConcurrentHashMap or AtomicInteger.
NIO.2 Files & JUnit 5 Assertions
String content = Files.readString(Path.of("config.json")); @Test void shouldRejectNegativeDiscount() { var ex = assertThrows(IllegalArgumentException.class, () -> applyDiscount(-5)); assertTrue(ex.getMessage().contains("Negative")); }Files.readString and writeString default to UTF-8 and automatically close underlying file handles.
Pitfall: Avoid manual try/catch + fail() blocks in tests; use JUnit 5 assertThrows and assertAll.