Intermediate
A quick-reference cheatsheet for modern Java (21 LTS): syntax, records, generics, collections, streams, Optional, exceptions, and virtual threads.
OOPGenericsCollectionsConcurrency
Types & Variables
Declarations
int i = 42;
double d = 3.14;
boolean flag = true;
char c = 'A';
long big = 1_000_000L;
String s = "text";
final double PI = 3.14159; // immutable
var name = "Ada"; // inferred (local only)
var list = new ArrayList<String>();
Primitives & Wrappers
byte short int long -> Byte Short Integer Long
float double -> Float Double
char boolean -> Character Boolean
Integer n = 5; // autoboxing
int x = n; // unboxing
Control Flow & Switch
if (x > 0) { ... } else { ... }
for (int i = 0; i < n; i++) { ... }
for (var item : list) { ... }
while (cond) { ... }
do { ... } while (cond);
Switch Expression (Java 21)
String r = switch (day) {
case 1, 7 -> "weekend";
case 2, 3, 4, 5, 6 -> "weekday";
default -> "?";
};
// pattern matching + guards
String describe(Object o) {
return switch (o) {
case Integer i when i > 100 -> "big";
case Integer i -> "int " + i;
case String str -> "str " + str.length();
case null -> "null";
default -> "other";
};
}
Classes & Records
public class Account {
private double balance;
public Account(double init) { this.balance = init; }
public double getBalance() { return balance; }
public void deposit(double a) { balance += a; }
}
// Record (immutable data carrier, Java 16+)
public record Point(int x, int y) {
public Point { // compact constructor
if (x < 0) throw new IllegalArgumentException();
}
}
var p = new Point(3, 4);
p.x(); p.y(); // auto accessors
Enums & Sealed
enum Dir { NORTH, SOUTH, EAST, WEST }
sealed interface Expr permits Num, Add {}
record Num(double v) implements Expr {}
record Add(Expr l, Expr r) implements Expr {}
Interfaces & Inheritance
abstract class Shape {
abstract double area();
}
interface Drawable {
void draw();
default void render() { draw(); } // default method
}
class Circle extends Shape implements Drawable {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
@Override public void draw() { }
}
Shape s = new Circle(2); // polymorphism
Access Modifiers
public // everywhere
protected // package + subclasses
(default) // package only
private // class only
Generics
class Box<T> {
private final T value;
Box(T v) { this.value = v; }
T get() { return value; }
}
Box<String> b = new Box<>("hi");
static <T> T first(List<T> xs) { return xs.get(0); }
// PECS: Producer extends, Consumer super
double sum(List<? extends Number> xs) { ... } // read
void fill(List<? super Integer> xs) { ... } // write
<T extends Comparable<? super T>> T max(List<T> xs) { ... }
Collections
| Interface |
Impl |
Notes |
List<E> | ArrayList | Indexed, ordered |
Set<E> | HashSet, TreeSet | Unique |
Map<K, V> | HashMap, TreeMap | Key-value |
Deque<E> | ArrayDeque | Stack/queue |
List<String> l = new ArrayList<>(); l.add("a");
Set<Integer> s = new HashSet<>();
Map<String, Integer> m = new HashMap<>();
m.put("k", 1);
m.getOrDefault("x", 0);
m.computeIfAbsent("y", k -> 0);
List<Integer> imm = List.of(1, 2, 3); // immutable
Streams
List<Integer> out = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.sorted()
.collect(Collectors.toList());
int total = nums.stream().reduce(0, Integer::sum);
long count = nums.stream().filter(n -> n > 3).count();
Map<Integer, List<String>> byLen = words.stream()
.collect(Collectors.groupingBy(String::length));
Optional
Optional<String> o = list.stream().findFirst();
o.map(String::toUpperCase).orElse("NONE");
o.ifPresent(System.out::println);
o.orElseThrow();
Optional<String> empty = Optional.empty();
Optional<String> of = Optional.ofNullable(maybeNull);
Exceptions
try (var r = Files.newBufferedReader(path)) { // try-with-resources
return r.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
cleanup();
}
throw new IllegalArgumentException("bad");
// checked -> extends Exception (must declare/catch)
// unchecked -> extends RuntimeException
Concurrency & Virtual Threads
Runnable task = () -> work();
new Thread(task).start();
try (var pool = Executors.newFixedThreadPool(4)) {
Future<Integer> f = pool.submit(() -> 42);
f.get();
}
CompletableFuture.supplyAsync(() -> fetch())
.thenApply(String::trim)
.thenAccept(System.out::println);
synchronized (lock) { ... }
volatile boolean running;
Map<String, Integer> safe = new ConcurrentHashMap<>();
Virtual Threads (Java 21)
Thread.startVirtualThread(() -> task());
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++)
ex.submit(() -> { Thread.sleep(1000); return call(); });
}
Build & Run Commands
javac Hello.java # compile
java Hello # run
java Hello.java # compile + run single file (11+)
jshell # interactive REPL
mvn clean package # Maven build + jar
mvn test # run JUnit tests
gradle build # Gradle build
gradle test # Gradle tests
java -jar app.jar # run a jar