Class UnnamedPatternsVariablesPreviewExamples
Sometimes Java syntax requires a variable name even though the program
intentionally ignores the value. Before this feature, developers often used
names such as ignored or unused. The underscore makes that
intent part of the language: the value is deliberately not available for
later use.
The feature became final in Java 22 as unnamed variables and patterns. This The syntax shown here is also the syntax that became final in Java 22, so it remains faithful to the Java 21 preview while this class preserves the historical preview label.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordLine record used by the unnamed record-pattern example.static final recordPoint record used by the unnamed record-pattern example. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionbooleancanParseInteger(String text) Uses an unnamed catch parameter when the exception object is not needed.intcountWithoutUsingElements(Iterable<String> values) Uses an unnamed variable where the value is intentionally ignored.booleanUses unnamed patterns for record components that are not needed.
-
Constructor Details
-
UnnamedPatternsVariablesPreviewExamples
public UnnamedPatternsVariablesPreviewExamples()
-
-
Method Details
-
countWithoutUsingElements
Uses an unnamed variable where the value is intentionally ignored.The loop visits every element, but the body only needs to count visits. The underscore says the element value is irrelevant.
- Parameters:
values- values to count- Returns:
- how many values were visited
-
canParseInteger
Uses an unnamed catch parameter when the exception object is not needed.The code only needs to know that parsing failed. It does not need the exception object itself.
- Parameters:
text- numeric text- Returns:
- whether the text can be parsed
-
startsAtX
Uses unnamed patterns for record components that are not needed.The first point's x coordinate is useful, but neither y coordinate nor the second point is needed. The underscores make those intentional omissions visible in the pattern.
- Parameters:
shape- value to inspectexpectedStartX- x coordinate required for the first point- Returns:
- whether the value is a line whose first point has the requested x coordinate
-