Do you know Java: Underscore as identifier
We could use underscore as a variable name until Java 7, but it cannot be used as an identifier from Java 9 and upwards.
Java has strict rules about how to name a variable, which characters are accepted in it or which one can be the first one. Underscore is a legal character among alphabetic characters and numbers. What if I did not use any other chars just underscore? Is that still valid variable name? Let us see what the compiler says.
Single Underscore
The source looks as follows:
class Main {
public static void main(String[] args) {
int _ = 1;
System.out.println(_);
}
}
Java 7
We get the following result of the compilation of the above code with Java 7.
Yep! It is empty without any warnings!
Java 9
If we compile the code with Java 9, the result looks like:
error: as of release 9, '_' is a keyword, and may not be used as an identifier
It seems as _
was introduced as a keyword in Java 9. We cannot use it as a variable name.
Multiple Underscores
What if we put multiple underscores next to each other?
class Main {
public static void main(String[] args) {
int __ = 1;
System.out.println(__);
}
}
Java 7
Compiling the above code with Java 7, we get very similar to the previous one. No warnings again!
Java 9
The result of the compilation here in case of Java 9 is more interesting. Though we get error if we use single underscore, but it compiles swimmingly if identifier consits of multiple underscores.
Though we cannot use single underscore from Java 9 as variable name, we still have the opportunity to use multiple underscores concatenated next one another as an identifier.
Code can be found: https://github.com/torokmark/do-you-know-java