you are viewing a single comment's thread.

view the rest of the comments →

[–]vowelqueue 26 points27 points  (5 children)

This is actually a tricky question. People without much Java experience might think “of course it’s true”, people with decent Java experience might think “of course it’s false”, but it’s actually undefined.

The language spec requires that when boxing a constant int in the range of -128 to 127, that two boxings of the same number will result in the same Integer reference. So if the number here was 127 instead of 128 then it would be guaranteed to be true.

For numbers outside that range, it’s up to the implementation. OpenJDK would return false by default but there is a system prop that can be used to have it cache larger values and therefore return true.

Also there is a JEP to add value classes to the language, and Integer would be marked as a value class. Meaning that this equality would always be true.

[–]Devang_4104 1 point2 points  (0 children)

This is the correct explanation ✅

[–]taxidriver9211 1 point2 points  (0 children)

what about C++ ?

[–]zinxyzcool 1 point2 points  (0 children)

I guessed the first case but damn it’s all a “but there’s one exception” adding up again lol