_
” as a keyword; it cannot be used as an identifier or variable name, preventing confusion and errors in code.Before Java 11:
Developers could use the underscore as a variable name, which often led to poor readability, especially in complex algorithms.
int _ = 10; // ✅ Valid in Java 8 and earlier (but discouraged) System.out.println(_); // Prints 10
After Java 11:
Using an underscore as an identifier will result in a compilation error, prompting developers to use more descriptive names.
int _ = 10; // ❌ Compilation error in Java 9 and later System.out.println(_);
Fix:
int stock = 10; // ✅ We're forced to use more descriptive, readable names System.out.println(stock);
Below is a Java class that was written using Java 8:
public class DataProcessorBefore { private int _; public DataProcessorBefore(int _) { this._ = _; } public int calculateSum(int[] _) { int __ = 0; for (int ___ : _) { __ += ___; } return __; } public double average(int[] _) { if (_.length == 0) return 0.0; int __ = calculateSum(_); return (double) __ / _.length; } public boolean searchValue(int[] _, int __) { for (int ___ : _) { if (___ == __) { return true; } } return false; } public static void main(String[] args) { int[] data = {1, 2, 3, 4, 5}; DataProcessorBefore _ = new DataProcessorBefore(0); System.out.println("Sum: " + _.calculateSum(data)); System.out.println("Average: " + _.average(data)); System.out.println("Search for 3: " + _.searchValue(data, 3)); } }
This class uses the underscore extensively as an identifier, despite being discouraged.
public class DataProcessorAfter { private int initialValue; public DataProcessorAfter(int initialValue) { this.initialValue = initialValue; } public int calculateSum(int[] data) { int sum = 0; for (int item : data) { sum += item; } return sum; } public double average(int[] data) { if (data.length == 0) return 0.0; int sum = calculateSum(data); return (double) sum / data.length; } public boolean searchValue(int[] data, int valueToFind) { for (int item : data) { if (item == valueToFind) { return true; } } return false; } public static void main(String[] args) { int[] data = {1, 2, 3, 4, 5}; DataProcessorAfter processor = new DataProcessorAfter(0); System.out.println("Sum: " + processor.calculateSum(data)); System.out.println("Average: " + processor.average(data)); System.out.println("Search for 3: " + processor.searchValue(data, 3)); } }
_
) is reserved, preventing its use as an identifier to enhance code readability._
allows for potential future syntax developments in Java, such as unnamed variables and patterns introduced in Java SE 22.