Understanding Modern Language Features
1. Using Switch Expressions
| Form | Detail |
|---|---|
| Arrow | case X -> expr; |
| Block + yield | Multi-statement branch |
| Exhaustive | Required when used as expression |
| No fallthrough | Each case independent |
2. Using Local Variable Type Inference (var)
| Allowed | Not Allowed |
|---|---|
| Local vars with initializer | Method params/return type |
| For-loop variables | Field declarations |
| Try-with-resources | Without initializer |
| Lambda params Java 11+ | null initializer alone |
3. Understanding var with Lambdas
| Form | Use |
|---|---|
(var x, var y) -> ... | Allows annotations on lambda params |
| Mixed types | Forbidden — all params or none |
| No type | vs (x, y) -> ... functionally same |
4. Using var in Try-with-Resources
Example: var with resource
try (var in = Files.newBufferedReader(path)) {
in.lines().forEach(System.out::println);
}
| Tip | Reason |
|---|---|
| Type inferred | Less verbose |
| Use sparingly | Lost type clarity hurts readability |
5. Using Private Interface Methods (Java 9+)
| Modifier | Use |
|---|---|
private | Helper for default methods |
private static | Helper for static methods |
| Visibility | Not exposed to implementers |
6. Using Default Methods in Interfaces
| Aspect | Detail |
|---|---|
| Syntax | default returnType m() { ... } |
| Diamond resolution | Class > interface; explicit I.super.m() |
| Use | API evolution without breaking |
| Cannot | Override Object methods |
7. Using Static Methods in Interfaces
| Rule | Detail |
|---|---|
| Not inherited | Call via interface name |
| Use | Factory methods (e.g., List.of) |
| Override | Cannot |
8. Using Enhanced Pseudo-Random Generators (Java 17+)
| API | Use |
|---|---|
RandomGenerator.of("L64X128MixRandom") | Modern algorithm |
RandomGeneratorFactory.all() | List available |
SplittableGenerator | Parallel streams |
JumpableGenerator | Skip-ahead |
9. Using Modern String Methods
| Method | Since | Use |
|---|---|---|
isBlank() | Java 11 | Empty or whitespace |
strip / stripLeading / stripTrailing | Java 11 | Unicode-aware trim |
lines() | Java 11 | Stream<String> |
repeat(n) | Java 11 | Repeat string |
formatted(args) | Java 15 | Instance form |
chars/codePoints | Java 8 | IntStream |
indent(n) | Java 12 | Add/remove indent |
10. Using Collection Factory Methods
| Factory | Result |
|---|---|
List.of(...) | Immutable list |
Set.of(...) | Immutable set |
Map.of(k1,v1,...) | ≤10 entries |
Map.ofEntries(Map.entry(k,v),...) | Many entries |
List.copyOf(coll) | Defensive immutable copy |