Java cheat sheet

A scannable Java reference: 27 short snippets across 12 topics, each linking back to the lesson it came from.

At a glance

TopicWhat it covers
Java: getting startedJava source compiles to bytecode, not machine code. The JVM (Java Virtual Machine) runs that bytecode, so the samelesson
Java types and variablesEvery primitive has a wrapper class (Integer, Double, Boolean…) so it can live in collections. The compiler convertslesson
Java collectionsHash-based collections find entries by hashCode() and confirm with equals(). Override one without the other and lookupslesson
Exceptions and try-with-resourcesEverything descends from Throwable. Error signals JVM-level problems you should not catch. Exception splits intolesson
Classes, records and interfacesA record is a compact immutable data carrier: the compiler generates the constructor, accessors, equals, hashCode andlesson
Setting up a modern Java toolchainA single LTS JDK installation is enough to compile, run, experiment and package. Distributions differ in licensing andlesson
Control flow, methods and the modern mainA compact source file allows top-level methods, gives the file an implicit unnamed class, and makes main instance-basedlesson
Dates, text and numbersjava.time types, formatting and parsing, BigDecimal for money, and text blocks for readable stringslesson
Files, I/O and JSONjava.nio.file Path and Files, buffered reading and writing, charsets, and serialising records to JSON safelylesson
Modules, packages and build configurationPackages and visibility, JPMS modules, multi-module Maven and Gradle builds, and producing a runnable jarlesson
Concurrency, virtual threads and structured concurrencyThreads and executors, CompletableFuture, virtual threads for I/O, structured concurrency scopes, and the races thatlesson
Testing, logging and JVM toolingJUnit 5 assertions and lifecycle, parameterised tests and mocks, SLF4J with Logback, and starting with JFRlesson

Quick snippets

Java: getting started

Your first class

// Hello.java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world");
    }
}

Your first class

javac Hello.java     # produces Hello.class
java Hello           # runs it; note: no .class suffix

Modern base syntax

// since Java 10: local variable type inference
var name = "Ada";
var scores = new int[]{90, 85, 77};

// text blocks (Java 15+) for multi-line strings
var message = """
    Line one
    Line two""";

// var still needs a type; it is not dynamic typing
// name = 42;  // compile error

Full lesson: Java: getting started →

Java types and variables

Eight primitives

int count = 10;
long big = 10_000_000_000L;   // underscores aid readability
double rate = 0.075;
char grade = 'A';             // single quotes, char only
boolean active = true;

Objects and autoboxing

Integer boxed = 1000;      // autoboxed
int unboxed = boxed;       // auto-unboxed

Integer a = 1000, b = 1000;
System.out.println(a == b);      // false: different objects
System.out.println(a.equals(b)); // true: same value

Integer c = 100, d = 100;
System.out.println(c == d);      // true: small values are cached (-128..127)

Strings and equality

String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1 == s2);      // false: reference comparison
System.out.println(s1.equals(s2)); // true: value comparison

// string pool: literals are interned and share storage
String joined = "a" + "b" + 1;     // "ab1"
String better = "%s has %d items".formatted("Cart", 3);

Full lesson: Java types and variables →

Java collections

Using them

var names = new ArrayList<String>();
names.add("Ada");
names.add("Grace");
names.add(0, "Alan");

var unique = new LinkedHashSet<>(names);
var byId = new HashMap<Integer, String>();
byId.put(1, "Ada");
byId.getOrDefault(99, "unknown");
byId.computeIfAbsent(2, k -> "created");

names.sort(Comparator.naturalOrder());

Using them

for (String n : names) System.out.println(n);
names.forEach(System.out::println);

var adults = people.stream()
    .filter(p -> p.age() >= 18)
    .map(Person::name)
    .toList();

equals and hashCode

public record User(int id, String email) {}   // equals/hashCode generated

// mutating a key after insertion makes an entry unreachable
var key = new MutableKey("a");
map.put(key, 1);
key.setName("b");
map.get(key);   // null - its hash changed

Full lesson: Java collections →

Exceptions and try-with-resources

Handling

try {
    int value = Integer.parseInt(text);
} catch (NumberFormatException e) {
    System.err.println("Not a number: " + text);
} finally {
    cleanup();          // always runs
}

// multi-catch for unrelated types
try { risky(); }
catch (IOException | SQLException e) { log(e); }

try-with-resources

try (var reader = Files.newBufferedReader(path);
     var conn = dataSource.getConnection()) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
} catch (IOException | SQLException e) {
    throw new UncheckedIOException(new IOException(e));
}

Full lesson: Exceptions and try-with-resources →

Classes, records and interfaces

Records and enums

public record Point(int x, int y) {
    public Point {
        // compact constructor: validate
        if (x < 0 || y < 0) throw new IllegalArgumentException("negative coords");
    }
    public double distanceFromOrigin() { return Math.hypot(x, y); }
}

public enum Status { ACTIVE, SUSPENDED, CLOSED }

Full lesson: Classes, records and interfaces →

Setting up a modern Java toolchain

One JDK, a handful of commands

java -version          # the launcher and the runtime
javac -version         # the compiler that ships with a JDK, not a JRE

java Hello.java        # single-file source: compile and run in one step
jshell                 # interactive REPL
javadoc -d docs src/main/java/com/example/*.java
jar --create --file app.jar -C out .

jshell and the IDE

jshell> var names = List.of("Ada", "Grace")
names ==> [Ada, Grace]
jshell> names.stream().map(String::toUpperCase).toList()
$2 ==> [ADA, GRACE]
jshell> /vars          # every variable defined so far
jshell> /methods       # and every method
jshell> /reset         # clear state
jshell> /exit

Full lesson: Setting up a modern Java toolchain →

Control flow, methods and the modern main

Compact source files and instance main

// Hello.java — a compact source file: no class declaration, no static, no args
void main() {
    String name = IO.readln("Name? ");
    IO.println("Hello, " + name);
}

Compact source files and instance main

java Hello.java        # compiles and runs in one step, no build file needed

Full lesson: Control flow, methods and the modern main →

Dates, text and numbers

java.time

Instant now = Instant.now();                                   // UTC timeline point
LocalDate today = LocalDate.now(ZoneId.of("Europe/London"));
LocalDateTime meeting = LocalDateTime.of(2026, 9, 18, 9, 30);

Duration elapsed = Duration.between(meeting, meeting.plusHours(2));   // PT2H
Period span = Period.between(LocalDate.of(2026, 1, 1), today);        // P8M17D

ZonedDateTime tokyo = meeting.atZone(ZoneId.of("Asia/Tokyo"));
Instant asInstant = tokyo.toInstant();

Formatting and parsing

DateTimeFormatter friendly =
    DateTimeFormatter.ofPattern("d MMM uuuu HH:mm", Locale.UK);

String text = meeting.format(friendly);              // "18 Sep 2026 09:30"
LocalDateTime parsed = LocalDateTime.parse(text, friendly);

String machine = DateTimeFormatter.ISO_INSTANT.format(Instant.now());

Full lesson: Dates, text and numbers →

Files, I/O and JSON

JSON with records

public record Customer(String id, String email, List<String> tags) {}

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new JavaTimeModule())
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

String json = mapper.writeValueAsString(customer);        // records serialise directly
Customer back = mapper.readValue(json, Customer.class);

Full lesson: Files, I/O and JSON →

Modules, packages and build configuration

Packages and visibility

package com.example.orders;          // the directory must match exactly

public class OrderService {

    public Receipt place(Order order) { ... }      // the published API
    Receipt recalculate(Order order) { ... }       // package-private helper

    private BigDecimal taxFor(Order order) { ... } // visible only inside this class
}

JPMS modules

// src/main/java/module-info.java
module com.example.orders {
    requires java.sql;
    requires transitive com.example.core;    // callers also see core

    exports com.example.orders.api;          // only this package is public
    opens com.example.orders.model to com.fasterxml.jackson.databind;

    uses com.example.orders.spi.Pricer;
    provides com.example.orders.spi.Pricer
        with com.example.orders.internal.SimplePricer;
}

Multi-module builds and runnable jars

<!-- parent pom.xml: the reactor builds these in dependency order -->
<modules>
  <module>core</module>
  <module>api</module>
</modules>

Full lesson: Modules, packages and build configuration →

Concurrency, virtual threads and structured concurrency

Threads and executors

Thread platform = Thread.ofPlatform().name("worker-1").start(() -> doWork());

try (var pool = Executors.newFixedThreadPool(8)) {
    Future<Integer> future = pool.submit(() -> compute());
    int result = future.get(2, TimeUnit.SECONDS);       // blocks, wraps failures
    pool.shutdown();
}

try (var virtual = Executors.newVirtualThreadPerTaskExecutor()) {
    for (Order order : orders) virtual.submit(() -> enrich(order));
}

CompletableFuture

var io = Executors.newVirtualThreadPerTaskExecutor();

CompletableFuture<Quote> quoted = CompletableFuture
    .supplyAsync(() -> fetchQuote(sku), io)
    .thenApply(Quote::withTax)
    .exceptionally(err -> Quote.failed(sku));

CompletableFuture<Void> all = CompletableFuture.allOf(a, b, c);
CompletableFuture<Object> fastest = CompletableFuture.anyOf(a, b);

Virtual threads and structured concurrency

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Supplier<User> user = scope.fork(() -> loadUser(id));
    Supplier<Orders> orders = scope.fork(() -> loadOrders(id));

    scope.join();                 // wait for every forked task
    scope.throwIfFailed();        // propagate the first failure
    return new Profile(user.get(), orders.get());
}

Full lesson: Concurrency, virtual threads and structured concurrency →

Testing, logging and JVM tooling

Logging and JVM tooling

private static final Logger log = LoggerFactory.getLogger(Checkout.class);

log.info("order placed id={} total={}", order.id(), total);
log.warn("upstream slow id={}", order.id());

try {
    gateway.charge(order, total);
} catch (PaymentException failure) {
    log.error("charge failed id={}", order.id(), failure);   // the throwable goes last
}

Logging and JVM tooling

<!-- logback.xml: one line per event, on stdout, for the platform to collect -->
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{ISO8601} %-5level [%thread] %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <root level="INFO"><appender-ref ref="STDOUT"/></root>
</configuration>

Full lesson: Testing, logging and JVM tooling →

FAQ

Is this Java cheat sheet free to use?
Yes. No sign-up and no tracking: the page is static, every example is on the page itself, and you can print it or save it as a one-page reference.
Where do the examples come from?
Every snippet is taken from the 12 lessons of the Java course on this site, and each section links back to the lesson it was pulled from.
How do I go deeper than a cheat sheet?
Open the full Java course — it carries the worked explanations, the edge cases and the exercises behind every line here.

Node.js PHP HTTP Go Rust Spring Boot

Last refreshed 2026-09-27.