Underscore Keyword

Underscore(_) can be used as a variable name in Java till Java 8 but from Java 9 release, underscore can't be used as an identifier or variable name.

Java makes underscore(_) as a reserved word since Java 9.

In Java 9 and later versions, if we use the underscore character ("_") as an identifier, the source code can no longer be compiled and the compiler will report a compile-time error.

Let's see some examples to understand, how the use of underscore as a variable is changed version after version.

Time for an Example: Java 8

In this example, we are using underscore(_) as a variable name and compile it using Java 8 version. See it executes fine and produces output.

public class Main { 
	public static void main(String[] args){
		
		int _ = 20;
		System.out.println(_);
		
	}
}


20

Example: Java 9

If we execute this example using Java 9 then compile throws a compile-time error that indicates that underscore is a reserved word and can not be used as a variable name.

public class Main { 
	public static void main(String[] args){
		
		int _ = 20;
		System.out.println(_);
		
	}
}


'_' should not be used as an identifier, since it is a reserved keyword from source level 1.8

Example:

If we use underscore with a variable name then compiler works fine. Using underscore in a variable like first_name is still valid. But using _ alone as the variable name is no more valid. See the example below.

public class Main { 
	public static void main(String[] args){
		
		int _a = 20;
		System.out.println(_a);
		
	}
}


20

Example:

In this example, we are using underscore with parameter names and executes. It works fine, see the example below.

public class Main {  
	public static void main(String[] args){
		
		int sum = add(10,20);
		System.out.println(sum);
	}   
	
	static int add(int _a, int _b) {
		return _a+_b;
	}
}


30