Hasnain Ali Bohra
Hasnain Ali Bohra

Reputation: 2180

String declaration in java with _ named

I have peace of code who does the concatanation of string :-

String _‎ = "Hello ";
String _‏ = "World";
String _‎‏ = " !!";
System.out.println(_‎‏+_‎‏+_‎‏+_‎‏+_‎+_‏+_‎‏);

The output of code is :-

!! !! !! !!Hello World !!

I have few question :-

  1. how can we declared the same named variable (_)
  2. how the output is calculated

Upvotes: 0

Views: 308

Answers (2)

user6073886
user6073886

Reputation:

This is just a stupid gimmicky trick:

The three underscores are all different characters/Strings, but look the same to the human eye.

If you print there values as a bytearray

System.out.println(Arrays.toString("_‎".getBytes()));
System.out.println(Arrays.toString("_‏".getBytes()));
System.out.println(Arrays.toString("_‎‏".getBytes()));

you will get the output:

[95, -30, -128, -114]
[95, -30, -128, -113]
[95, -30, -128, -114, -30, -128, -113]

The code you posted is therefore equivalent to the following:

String a = "Hello ";
String b = "World";
String c = " !!";
System.out.println(c+c+c+c+a+b+c);

Upvotes: 17

Khemraj Sharma
Khemraj Sharma

Reputation: 58934

Starting from Java 9 underscore is strictly not allowed (See Java 9 documentation)

The underscore character is not a legal name.

If you use the underscore character ("_") an identifier, your source code can no longer be compiled.

I tried to run this and got error.

(use of '_' as an identifier might not be supported in releases after Java SE 8)

So good for you not to use underscore from now.

Obviously, If they said not to use underscore, then there is some reason behind this.

Upvotes: 2

Related Questions