In this post, we will see about Underscore
keyword, which is introduced in java 9.
Underscore In Java
Underscore(_)
is a symbol that is used to combine multi-words in a single identifier
sometimes refers to a variable in a programming context.
In Java, to create a lengthy variable, we prefer to use underscore (_)
such as employee_id
, employee_name
etc.
Apart from it, underscore
can be used to represent a variable and can hold any type of value . Since Java 8, we could use underscore as variable name such as = 10, = 10.5, etc. But in Java 9, underscore is a reserve word
and cannot
be used as an identifier.
Let’s see an example.
Underscore as variable in Java 8
This example is executed by using Java 8 and produce output with a warning message. See the output.
1 2 3 4 5 6 7 8 |
public class Main{ public static void main(String[] args) { int _ = 10; // valid till Java 8 System.out.println(_); } } |
Output
warning: ‘_’ used as an identifier
(use of ‘_’ as an identifier might not be supported in releases after Java SE 8)
Underscore as variable in Java 9
If we execute this example with Java 9 then it reports an error. See the example.
1 2 3 4 5 6 7 8 |
public class Main{ public static void main(String[] args) { int _ = 10; // valid till Java 8 System.out.println(_); } } |
Output
Although, we can not use underscore
alone as a variable name, but we can use it with other alphabets. See some possible examples.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main{ public static void main(String[] args) { int _a = 10; // valid System.out.println(_a); int a_ = 20; // valid System.out.println(a_); int a_b = 20; // valid System.out.println(a_b); int _ = 10; // invalid System.out.println(_); } } |
10
20
20
Error: ‘_’ should not be used as an identifier, since it is a reserved keyword from source level 1.8 on
That’s all about Java 9 underscore keyword.