How to use _ (underscore) as variable name in Java

Java 9 changes the characteristics of the Java language, and removing the underscore from the legal name is a major change made by Oracle.

  • The use of variable names _ in any context is never encouraged.
  • The latest version of Java reserves this name as a keyword and/or gives it special semantics. If you use the underscore character ("_") as an identifier, your source code will no longer be compiled. You will get compile-time errors.

Using underscore as variable name in Java 8

Although it is supported in Java 8, if you use _ as an identifier, a mandatory warning will be issued, telling you that "the use of ‘_’ as an identifier may not be supported in versions after Java SE 8." (Refer to JDK-8005852 to treat ‘_’ as an identifier)

 

// Java program to illustrate
// using underscore as
// variable name
class UnderScore_works
{
	public static void main(String args[])
	{
		int _ = 10;
		System.out.println(_);
		
	}		
}

Output:

10

Using underscore as variable name in Java 9

In Java 9, underscore as variable name won’t work altogether. Below source code can no longer be compiled.

 

// Java program to illustrate
// using underscore as
// variable name in java 9
class UnderScore_dont_works
{
	public static void main(String args[])
	{
		int _ = 10;
		System.out.println(_);
		
	}		
}

Important points:

  • Using underscore during a variable like first_name remains valid. But employing a alone as variable name is not any more valid.
  • Even if you're using earlier versions of Java, using only underscore as variable name is simply plain bad sort of programming and must be avoided.

 

Submit Your Programming Assignment Details