JaJava · Lesson 9 of 9

Java Cheatsheet

Modern Java (17+) on one page — records, streams, collections.

Java
// ── Basics ──────────────────────────────
public class Main {
    public static void main(String[] args) {
        int x = 42;
        double pi = 3.14;
        String name = "Ada";
        boolean ok = true;
        var list = new ArrayList<String>();   // inference
        System.out.println(name + " is " + x);
        String s = String.format("%s: %d", name, x);
    }
}

// ── Control flow ────────────────────────
if (x > 10) { } else if (x > 5) { } else { }
for (int i = 0; i < 5; i++) { }
for (String item : items) { }        // for-each
while (cond) { }

// switch expressions (14+):
String size = switch (n) {
    case 1, 2 -> "small";
    case 3    -> "medium";
    default   -> "large";
};

// ── Records (16+) — data classes ────────
record Point(int x, int y) { }
var p = new Point(1, 2);
p.x(); p.equals(q); // toString/equals/hashCode free
Java
// ── Classes & interfaces ────────────────
public class Dog extends Animal implements Comparable<Dog> {
    private final String name;
    public Dog(String name) { this.name = name; }
    public String bark() { return name + " woofs"; }
    @Override public int compareTo(Dog o) {
        return name.compareTo(o.name);
    }
}

// ── Collections ─────────────────────────
List<Integer> nums = new ArrayList<>(List.of(3, 1, 4));
nums.add(1); nums.get(0); nums.size(); nums.contains(4);
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 17); ages.getOrDefault("Eve", 0);
Set<Integer> seen = new HashSet<>();

// ── Streams ─────────────────────────────
List<String> honorRoll = students.stream()
    .filter(s -> s.grade() >= 90)
    .map(Student::name)                 // method reference
    .sorted()
    .toList();
int total = nums.stream().mapToInt(Integer::intValue).sum();
Optional<Student> best =
    students.stream().max(Comparator.comparing(Student::grade));

// ── Exceptions & misc ───────────────────
try (var reader = Files.newBufferedReader(path)) {  // auto-close
    ...
} catch (IOException e) {
    throw new RuntimeException("read failed", e);
}
Optional.ofNullable(x).orElse(fallback);

// javac Main.java && java Main   |  or: jshell to explore