var — local type inference (Java 10)#
var map = new HashMap<String, List<Integer>>(); // the compiler infers HashMap<String, List<Integer>>
for (var e : map.entrySet()) { ... }var is still statically typed (Java Basics Ch 2) — the type is fixed at compile time; you just don't write it. Only for local variables
with an initialiser (not fields, parameters or return types). Use it when the type is obvious from the right-hand side; avoid it when it hides meaning
(var x = service.process(); — process returns what?).
Text blocks (Java 15)#
String json = """
{
"name": "Priya",
"score": 200
}""";Multi-line strings with no \n or escaped quotes; the common leading indentation is removed. Great for JSON, SQL and prompts to AI models
(Prompt Engineering (coming soon)).
Switch expressions (Java 14) and yield#
Beyond Java Basics Ch 5: when a case needs several statements, use a block and yield its value:
String kind = switch (day) {
case 1, 7 -> "weekend";
default -> {
String t = day < 1 || day > 7 ? "invalid" : "weekday";
yield t; // the value of this case
}
};
// weekday (for day = 6)Pattern matching for instanceof (Java 16)#
From Object-Oriented Programming Ch 4, with a condition chained on:
Object o = "StudyBuddy";
if (o instanceof String s && s.length() > 5) System.out.println("long string: " + s); // long string: StudyBuddyHandy additions#
" ".isBlank() // true (Java 11: empty or only whitespace)
" hi ".strip() // "hi" (Unicode-aware trim)
"ab".repeat(3) // "ababab"
"a\nb\nc".lines().count() // 3
List.of / Set.of / Map.of // immutable factories (Java 9 — 07_java_collections_internals.md Ch 2)
List<Integer> seq = new ArrayList<>(List.of(1, 2, 3)); // Java 21 "sequenced collections":
seq.getFirst() seq.getLast() seq.reversed() // 1 3 [3, 2, 1]