Cheatsheet: Java

Last updated 2026-08-15

Variables and Types

Primitives and objects

int age = 30;
double price = 19.99;
boolean active = true;
String name = "Alice";
Integer boxed = age;

Type inference with var

var message = "Hello";
var numbers = List.of(1, 2, 3);
var total = 0;

Records for simple data

record User(String name, int age) {}

var user = new User("Alice", 30);

Control Flow

if / else

int score = 88;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}

for and enhanced for

for (int i = 0; i < 3; i++) {
    System.out.println(i);
}

for (String item : List.of("a", "b")) {
    System.out.println(item);
}

switch expression

String day = "SAT";
String kind = switch (day) {
    case "SAT", "SUN" -> "weekend";
    default -> "weekday";
};

while loop

int count = 0;
while (count < 3) {
    count++;
}

Collections

List

var names = new ArrayList<>(List.of("Ana", "Ben"));
names.add("Cara");
String first = names.get(0);

Map

var counts = new HashMap<String, Integer>();
counts.put("apple", 2);
counts.merge("apple", 1, Integer::sum);
int total = counts.getOrDefault("pear", 0);

Set

var tags = new HashSet<>(Set.of("java", "backend"));
tags.add("jvm");
boolean hasJava = tags.contains("java");

Classes and Objects

Class with constructor

class User {
    private final String name;

    User(String name) {
        this.name = name;
    }

    String greet() {
        return "Hi, " + name;
    }
}

Inheritance

class AdminUser extends User {
    AdminUser(String name) {
        super(name);
    }
}

Interface implementation

interface Speaker {
    String speak();
}

class Dog implements Speaker {
    public String speak() {
        return "woof";
    }
}

Streams and Lambdas

Filter and map

var result = List.of(1, 2, 3, 4).stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * 10)
    .toList();

Collectors

var grouped = List.of("apple", "apricot", "banana").stream()
    .collect(Collectors.groupingBy(word -> word.charAt(0)));

Method references

List.of("a", "b", "c").forEach(System.out::println);

Exception Handling

try / catch / finally

try {
    Files.readString(Path.of("input.txt"));
} catch (IOException e) {
    System.err.println(e.getMessage());
} finally {
    System.out.println("done");
}

Checked vs unchecked

void load() throws IOException {
    Files.readString(Path.of("input.txt"));
}

throw new IllegalArgumentException("bad input");

try-with-resources

try (var reader = Files.newBufferedReader(Path.of("input.txt"))) {
    String line = reader.readLine();
}

String Formatting

String.format

String text = String.format("%s has %d tasks", "Alice", 3);

Formatted strings

String report = "Total: %d items".formatted(42);

Text blocks

String json = """
    {
      \"name\": \"Alice\"
    }
    """;