A minor but helpful feature that improves code readability. Unnamed variables are represented by an underscore _. They are used in scenarios where the value assigned to a variable is unimportant, and only the side effect of the assignment matters.

Benefits of Unnamed Variables

  • Enhanced Readability: By using underscores for unused variables, you make it clear that their values aren't being used elsewhere in the code. This reduces clutter and improves code maintainability.
  • Conciseness: Unnamed variables eliminate the need to declare variables solely for the purpose of discarding their assigned values. This keeps code more concise.

Common Use Cases

  • Side Effects: Unnamed variables are particularly useful when dealing with side effects. For instance, removing an element from a queue where you only care about the removal itself:

    final var list = new LinkedList<>();
    list.add("Example");
    var _ = list.remove(); // Using unnamed variable.
  • Enhanced for Loops: You can use unnamed variables in enhanced for loops to iterate through collections without needing the individual elements themselves. Here's an example:

    var items = Arrays.asList("Item1", "Item2", "Item3");
    for (var _ : items) {
    // Perform some action without needing the iterated item itself
    }
  • try-with-resources: Unnamed variables can be used with try-with-resources statements to ensure proper resource closure without needing a variable to hold the resource. For example:

    try (var _ = new Scanner(System.in)) {
      // Use the scanner to read input from standard input (console) but not interested with its value.
    }
  • Lambda Expressions: In lambda expressions, unnamed variables indicate that you're not interested in the parameter's value. The focus is on the lambda's body. Here's an example:

    var items = Arrays.asList("Item1", "Item2", "Item3");
    items.forEach(_ -> System.out.println("Processing number")); //Not interested the with the item value.

Overall, unnamed variables are a simple yet effective tool for writing cleaner, more concise, and readable code.