web
 

Java 8 Stream - Java Stream


What is the use of Underscore (“_”) in Java Modifiers? Changes to underscore in Java SE 9 release with some simple and useful examples. I have already released many Java SE 9 tutorials. Please go through them to learn all Java SE 9 new features.

Introduction to Underscore (“_”) in Java

In Java, we can start an identifier with a letter, dollar sign ($) or underscore (“_”). However, Identifiers cannot start with a number.

In Java, we can use underscore in identifiers mainly the following cases:

  • To connect two different words of an identifier.
  • To define constants.
  • To define some lengthy and useful identifier (mostly in unit tests).
  • To define private variables, methods etc.

Before Java SE 8: Underscore (“_”)

Before Java SE 8 release, we can use Underscore in identifiers. And also we can use Underscore alone as an identifier without any issues. Even though it is not recommended, but it works fine without any issues.

public class Java8UnderscoreTest { public static void main(String[] args) { int _ = 10; System.out.println("Value of underscore (_) = " + _); } }

Output:-


Value of underscore (_) = 10

It works fine without any issues. However, we can see the following warning messages in IDEs.


Multiple markers at this line
- '_' should not be used as an identifier, since it is a reserved keyword from source level 1.8 on
- Occurrence of '_'

That means Underscore is not allowed as an identifier from Java SE 8 on-wards.

NOTE:-

It is a compile-time error if a Lambda Parameter has the name underscore (“_”).

Java SE 9: “_” Changes

Oracle Corp is going to remove that underscore (“_”) usage as identifier completely in Java SE 9 release.

NOTE:- Disallowing “_” as a legal identifier



jshell> int _ = 10
|  Error:
|  as of release 9, '_' is a keyword, and may not be used as an identifier
|  int _ = 10
|      ^
|  Error:
|  reached end of file while parsing
|  int _ = 10





journaldev is optimized for learning.© journaldev .
All Right Reserved and you agree to have read and accepted our term and condition