DEV Community

loading...

Java String Puzzle

awwsmm profile image Andrew (he/him) ใƒป1 min read

Eclipse posted this Java puzzle to Twitter today:

...do you know what will be printed without coding it and trying it?

Discussion

pic
Editor guide
Collapse
perkinsjr profile image
James Perkins

that one should throw a NPE exception at line 10. Almost had me but then I read it again.

Collapse
bertilmuth profile image
Bertil Muth

b canโ€˜t possibly be true. Can it? :-)

Collapse
deciduously profile image
Ben Lovy

I don't know anything about Java. Why not? To the completely untrained eye it sure looks true.

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
Thread Thread
bertilmuth profile image
Bertil Muth

Interesting, thanks for sharing!

Collapse
jrtibbetts profile image
Jason R Tibbetts

NullPointerException for Y.equals(null).

Collapse
devit951 profile image
Ildarov

You can't invoke any method on null reference object :)

Collapse
thefern profile image
Fernando B ๐Ÿš€

Gonna say True. Though not sure if b is True 100% lol

Collapse
samwho profile image
Sam Rose

False. :)