DEV Community

Discussion on: Java String Puzzle

Collapse
 
bertilmuth profile image
Bertil Muth

Java has 2 ways of determining if two objects are “the same”. The == operator, and the equals method. Both work differently, and both are shown in the example.

The == operator compares object identity. Creating two String objects and comparing them with == would return false, even if the text is „ABC“ both times. Like: two persons can both be called „Martin Fowler“, but have distinct identities.

So, my first instinct told me: there are multiple occurrences of “ABC”. So multiple String objects. So the == returns false. Then, Java doesn’t even evaluate the second and operand (after &&). The result of the riddle: false is printed.

Then I looked at the riddle again. Java does heavy optimizing. Strings in Java are immutable, and in the example, “ABC” is not changed. So chances are that there only is exactly 1 “ABC” object.

In that case, the == yields true and the second and operand (with Y) is evaluated. And because Y is null, and calling any method (including equals) on null throws a NullPointerException...

The riddles answer is: nothing is printed. A NullPointerException is thrown.

I guess :-) Am I right?

Thread Thread
 
awwsmm profile image
Andrew (he/him)

The answer lies in the Java String pool!

Thread Thread
 
bertilmuth profile image
Bertil Muth

Interesting, thanks for sharing!