Unnamed variables
These 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
int _ = 10;
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:
// Java Program to Illustrate the Use
// Of Unnamed Variables
import java.util.Arrays;
import java.util.List;
// Driver Class
public class UnnamedVariables {
// Main Function
public static void main(String[] args) {
List<String> names = Arrays.asList("Shivansh", "Ramesh", "Aakash");
// Using a valid variable name to iterate over the list
for (String name : names) {
System.out.println("Hello " + name);
}
}
}
Output
Hello Shivansh Hello Ramesh Hello Aakash
Unnamed Patterns and Variables in Java
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.
Contact Us