Modern Java Features
Unnamed Patterns and Variables
Learn to use the underscore character (_) for unused variables in pattern matching and catch blocks.
Interview: Commonly tested on compiler rules: where underscore is allowed as a variable placeholder (Java 22).
Introduced in Java 22, Unnamed Patterns and Variables allow using the underscore character (_) to stand in for unused variables in declarations, improving readability and code clarity.
Core Idea
The underscore acts as a compiler-recognized placeholder for variables that must be declared but are not read.
Why It Matters
Prevents warnings from static analysis tools (like SonarQube) regarding unused parameters.
Interview Lens
Tests syntax rules: where the underscore is legal (catch blocks, patterns, loops) vs illegal.
Use Case Scenarios
- Catch Blocks: Suppressing unused exception parameters (e.g.
catch (NumberFormatException _)). - Lambda Parameters: Declaring lambdas where arguments are ignored (e.g.
(k, _) -> value). - Pattern Matching: Unpacking records while ignoring specific fields.
Code Walkthrough
This program demonstrates using unnamed variables in catch blocks and lambdas.
Interview-Relevant Information
Q: Can you read a value from an unnamed variable?
Answer: No. The underscore (_) is not a valid variable name; it is an unnamed identifier. The compiler prevents any attempt to read or reference _ inside your code, throwing a compilation error.
Quick Checklist
Where can you use an underscore to ignore variables? Can you read the value of an unnamed variable? If yes, you understand Java 22 Unnamed Patterns.
Use Cases
Simplifying event listener handlers with unused arguments.
Ignoring fields when unpacking record classes in pattern matching.
Common Mistakes
Attempting to read from the underscore variable (e.g. System.out.println(_)), which is a compile error.
Using underscore in Java versions prior to Java 22 where it was either a keyword or a reserved symbol.