nus-cs2030 / 2021-s1

27 stars 48 forks source link

basic java equality condition #513

Open cl-xy opened 4 years ago

cl-xy commented 4 years ago

Description

Hi! Im slightly confused about the equality condition in java. For this question, the ans is C. I would like to find out when will x == y evaluate to true, and when x == y evaluate to false. Any help is appreciated, thank you!!

Screenshots (if any):

image

CWei88 commented 4 years ago

You can check out something called Java Integer Cache: https://javapapers.com/java/java-integer-cache/

sushmit98 commented 4 years ago

Hi! If in the question, int was used instead of Integer, would the answer have been A then?

cl-xy commented 4 years ago

@sushmit98 yep should be!

tomjoju commented 4 years ago

If the value of i was between -127 and 127, the integer object will be cached internally and reused via the same object. So, when Integer x = i and Integer y = i are run, in effect, the same cached object will be returned and x and y will be referring to the same object. In this case, x == y will evaluate to true.

On the other hand, for any value of i outside this range, no cache will be created and 2 new objects will be created. As such, x == y will evaluate to false. Do check this link out: https://www.javamadesoeasy.com/2015/09/java-caches-integer-objects-formed-from.html

pikasean commented 4 years ago

Just a fun fact, this is actually one example of "interning", and this can happen to Strings too!

Check this out!