![]() |
Java programming language offers multiple features that allow developers to write rich and concise code. Among these features, there are unnamed patterns and variables which enables developers to work with data in a more flexible and elegant way. In this article, we will study about unnamed patterns and variables in Java and how they can be used effectively. Unnamed variablesThese are related features to unnamed patterns which allow developers to use placeholder variables without assigning names to them explicitly. This can be useful in various situations where a variable name is not necessary or the value of variable is not going to be used. Example of Unnamed Variables:Similar to unnamed patterns, Unnamed variables are denoted by the underscore character ‘_’. // unnamed variables In the above example, the ‘_’ is used as a placeholder for each element in the names list. Since the value of the variable is not used within the loop, using an unnamed variable makes the code more concise. Below is an example of an Unnamed Variables:
Output Hello Shivansh Hello Ramesh Hello Aakash Unnamed PatternsPatterns in Java are mainly associated with switch expressions and instanceof operators. Unnamed patterns that are introduced in Java 14 as preview features and made stable in Java 16 which extend the concept of patterns by allowing developers to match values without binding them to variables explicitly. Example of Unnamed PatternIt uses the underscore character ‘_’ as a wildcard to match any value without binding it to a variable. In the above example, the ‘_’ pattern matches any value of ‘x’ that is not explicitly handled by the previous cases. It acts as a wildcard pattern. Below is an example of an Unnamed Pattern:
Output Person's name is: Alice Person is older than 20 years old. Frequently Asked Question1. When Should I use unnamed patterns and variables?
2. Can We use unnamed patterns and variables in all java versions?
3. Are unnamed patterns and variables recommended for all situations?
|
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |