https://jaxenter.com/5-weird-java-questions-that-make-your-head-spin-121270.html
Integer a =
42
;
Integer b =
42
;
System.out.println(a == b); // yes
Integer c =
666
;
Integer d =
666
;
System.out.println(c == d);// false
The Integer type keeps a cache of all objects with a value in the range of -128 to 127 for performance reasons. So when you declare new variables in that range, you’re actually referring to the same object.
char
ch =
'0'
;
// ASCII for ‘0’ is 48
ch *=
1.1
;
// 48 x 1.1 is 52.8 which turns to 52 when cast to char
System.out.println(ch);
// 52 represents ‘4’ in ASCII
String _ = "Hello " ; String _ = "World" ; String _ = " !!" ; System.out.println(_+_+_); |
Spoiler alert: It prints out “Hello World !!”
How come _, _ and _ are different variables? You might have guessed it right. The answer is with hidden characters that pass on as legit Java identifiers.
1
2
| if (x != (x += 0 .0f)) System.out.println( "WTF" ); |
You can use any String, and also an int or long of (1 << 24) + 1 works for these types as their respective smallest value. But the smallest value of them all is Double.MIN_VALUE which is rounded to 0.0f when cast to a float.