Java Cheat Sheet
A searchable, printable Java reference — types, strings, collections, streams, records, pattern matching, concurrency and file I/O. Free.
Basics & types
10var list = new ArrayList<String>();
int x = 42; double d = 3.14;
long big = 9_000_000_000L;
char c = 'A'; boolean ok = true;
final int MAX = 100;
int i = (int) 3.99;
double d = x;
int n = Integer.parseInt("42");
String s = String.valueOf(42);
Integer boxed = 42; int y = boxed;
Strings & text blocks
12s.length(); s.charAt(0);
s.substring(1, 3)
s.contains("x"); s.startsWith("a");
s.replace("a", "b")
s.strip()
s.split(",")
String.join(", ", parts)
"ab".repeat(3)
s.isBlank(); s.isEmpty();
"%s: %d".formatted(key, count)
String html = """\n <p>Hi</p>\n """;
new StringBuilder().append(a).append(b)
Collections
12List<String> l = List.of("a", "b");
Map<String, Integer> m = Map.of("a", 1);
Set<Integer> s = Set.of(1, 2, 3);
new ArrayList<>(List.of("a", "b"))
List.copyOf(list)
map.getOrDefault(key, 0)
map.computeIfAbsent(k, x -> new ArrayList<>())
map.merge(key, 1, Integer::sum)
list.removeIf(s -> s.isBlank())
list.sort(Comparator.naturalOrder())
for (var e : map.entrySet())
list.forEach(System.out::println)
Streams & lambdas
12list.stream().map(String::toUpperCase).toList()
.filter(n -> n > 0)
.sorted(Comparator.comparing(User::name))
.distinct().limit(10).skip(5)
.collect(Collectors.groupingBy(User::city))
.collect(Collectors.joining(", "))
.collect(Collectors.toMap(User::id, u -> u))
.flatMap(List::stream)
.mapToInt(Order::total).sum()
.reduce(0, Integer::sum)
.anyMatch(s -> s.isBlank())
IntStream.range(0, 10)
Records & sealed classes
9record Point(int x, int y) {}
var p = new Point(1, 2); p.x();
equals(), hashCode(), toString()
record Range(int lo, int hi) { Range { if (lo > hi) throw new IllegalArgumentException(); } }
record Point(...) implements Shape {}
static Point origin() { return new Point(0, 0); }
sealed interface Shape permits Circle, Square {}
final class Circle implements Shape {}
non-sealed class Square implements Shape {}
Pattern matching & switch
8if (obj instanceof String s) use(s);
int n = switch (day) { case MON -> 1; default -> 0; };
case MON, TUE -> "early week";
case X -> { ...; yield value; }
case String s when s.length() > 2 ->
case Point(int x, int y) -> x + y;
case null, default -> "none";
switch (shape) { case Circle c -> ... }
OOP essentials
11interface Greeter { default String hi() { return "hi"; } }
class Impl implements A, B {}
class Admin extends User {}
@Override public String toString()
super.method(); super(args);
class Box<T> { T value; }
<T extends Comparable<T>> T max(...)
List<? extends Number> nums
enum Status { ACTIVE, DONE }
abstract class Base { abstract void run(); }
public static User of(String n) { ... }
Optional
10Optional.of(v); Optional.empty();
Optional.ofNullable(maybeNull)
opt.isPresent(); opt.isEmpty();
opt.orElse(defaultValue)
opt.orElseGet(() -> compute())
opt.orElseThrow()
opt.map(User::name).filter(n -> !n.isBlank())
opt.ifPresent(v -> use(v))
opt.ifPresentOrElse(use, this::warn)
opt.get()
Exceptions & try-with-resources
9try { ... } catch (IOException e) { ... }
catch (IOException | SQLException e)
finally { cleanup(); }
try (var in = Files.newBufferedReader(p)) { ... }
throw new IllegalArgumentException("bad id");
class AppException extends RuntimeException {}
RuntimeException vs Exception
e.getMessage(); e.getCause();
Objects.requireNonNull(x, "x is required")
Concurrency
12Thread.startVirtualThread(() -> work());
Executors.newVirtualThreadPerTaskExecutor()
var pool = Executors.newFixedThreadPool(4);
Future<T> f = pool.submit(task); f.get();
CompletableFuture.supplyAsync(() -> fetch())
.thenApply(r -> parse(r))
.thenCombine(other, (a, b) -> a + b)
.exceptionally(e -> fallback)
CompletableFuture.allOf(f1, f2).join();
new AtomicInteger().incrementAndGet()
new ConcurrentHashMap<K, V>()
synchronized (lock) { ... }
I/O & files (java.nio)
12Path p = Path.of("data", "file.txt");
String s = Files.readString(p);
Files.writeString(p, text);
List<String> lines = Files.readAllLines(p);
try (var st = Files.lines(p)) { ... }
Files.exists(p); Files.size(p);
Files.createDirectories(dir);
Files.copy(src, dst); Files.move(src, dst);
Files.deleteIfExists(p);
try (var files = Files.list(dir)) { ... }
Files.walk(dir)
Files.createTempFile("up-", ".tmp")
Build & CLI
12javac Main.java && java Main
java Main.java
java -jar app.jar
java -Xmx512m -jar app.jar
jshell
mvn clean package
mvn test
mvn dependency:tree
./gradlew build
./gradlew test --tests "UserTest"
jar tf app.jar
java --version
No entry matches “:q”.
About Java Cheat Sheet
This Java cheat sheet compresses modern Java into one searchable page: basics and types, strings and text blocks, collections, streams and lambdas, records and sealed classes, pattern matching and switch, OOP essentials, Optional, exceptions and try-with-resources, concurrency, file I/O with java.nio, and the build and CLI commands.
It covers both the fundamentals you write every day — a List, a HashMap, a for-each loop, a try-with-resources block — and the newer language features that changed how Java reads, including records, sealed types, switch expressions with pattern matching and text blocks.
The sheet is free and client-side: filter rows live with the search box, hop between sections with the sticky table of contents, copy any snippet with one click and print the page for a reference beside your keyboard.
How to use Java Cheat Sheet
- Skim the sections, from Basics & types and Collections through Concurrency to Build & CLI.
- Search for a keyword such as stream, record or Optional to filter every row live.
- Jump to Pattern matching & switch or Streams & lambdas when you need the modern syntax.
- Click a snippet or its copy icon to copy the Java code to your clipboard.
- Print the sheet for an offline Java reference.