Why you should stop using underscore as variable name in Java

15 / Sep / 2015 by Aseem Bansal 3 comments

There is a programming practice in many languages that if in a function call you don’t care about the variable’s value then use _ to denote this. This convention is usually used where lambdas are used.

Some people may be using this in Java also. If you are using it then you should stop. You must be asking why? Simply because underscore has been reserved for future use starting from JDK 8. Suppose you have the below

[code]
void someMethod(int _) {
// Something
}
[/code]

The above will give warning under JDK8 and as part of upcoming JDK 9 release this will become a compiler error. This is not a tentative change. It has been implemented in JDK9 under JEP 213 – Milling Project Coin. If you have many places where you are using _ as a convention then all of that will break.

Using underscore in a variable like a_b is still valid. But using _ alone as variable name is no more valid.

You have been warned.

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Uday Ogra

    I have written simple java code to find out if underscore has been used as an identifier in your code base or not

    Reply
  2. Parampreet

    Nice blog. Just a quick question what would happen if we are using more than 1 underscore a variable like String __ or Integer ___

    Reply
    1. Bhagwat Kumar

      From the summary at openjdk.java.net/jeps/213

      …. using underscore (“_”) as an identifier, which generates a warning as of Java SE 8, should be turned into an error in Java SE 9.

      It doesn’t say anything about identifier name having more than one character and starting with “_” character. So “__” identifier should be a valid identifier.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *