Since Java 9, the purpose of using ‘Underscore’ has been changed. With any version before Java 9, It can be used to create a variable or as an identifier. But, NO MORE. In Java 9, ‘Underscore’ is a keyword. In this article, we are going to see how it’s usage changed through various versions.
Check out: Iterate / ofNullable operations in Java 9 Stream
Underscore is a KEYWORD now since Java 9...!!! Share on X
Usage in Java 7
In Java 7, it could be used to used as an identifier or creating variable. Below code will compile & execute completely fine.
1 2 3 4 5 6 7 8 9 10 11 12 | public class Underscore_Java7_Example { public static void main(String[] args) { //Create variable with 'underscore' int _ = 50; System.out.println("Value of Underscore: " + _); } } |
Output:
1 | Value of Underscore: 50 |
Usage in Java 8
In Java 8, Oracle developers added the warning message that will be displayed when we execute the below code. Below code will compile perfectly fine but will show the warning message on execution.
1 2 3 4 5 6 7 8 9 10 11 12 | public class Underscore_Java8_Example { public static void main(String[] args) { //Create variable with 'underscore' int _ = 50; System.out.println("Value of Underscore: " + _); } } |
Output:
1 2 3 4 | Underscore_Java8_Example.java:6: warning: '_' used as an identifier int _ = 50; ^ (use of '_' as an identifier might not be supported in releases after Java SE 8) |
Usage in Java 9
In Java 9, ‘Underscore’ is a keyword therefore below code won’t compile and will throw the error message.
1 2 3 4 5 6 7 8 9 10 11 12 | public class Underscore_Java9_Example { public static void main(String[] args) { //Create variable with 'underscore' int _ = 50; System.out.println("Value of Underscore: " + _); } } |
Output:
1 2 | Underscore_Java9_Example.java:6: error: as of release 9, '_' is a keyword, and may not be used as an identifier int _ = 50; |
Underscore is a KEYWORD now since Java 9...!!! Share on X
Do you like this Post? – then check my other helpful posts:
- dropWhile / takeWhile operations in Java 9 Streams
- Collection sorting using Lambda in Java 8
- Iterate / ofNullable operations in Java 9 Streams