I have been told to never use ==
for strings but for everything else because .equals
would compare the values rather than the instances of the object. (Which I understand the difference of).
According to some sites, ==
compares memory locations?
What I don't understand is if you're comparing an integer with another, why would it compare memory locations, or is this just for strings?
If you're comparing int 3 to int 4 obviously it wouldn't be in the same memory location, but then if you're comparing int 4 to int 4, does that mean all integers with the value of 4 is stored in the same memory location?
According to some sites,
==
compares memory locations?
The expression a == b
compares the content of a
and b
, regardless of their types.
What I don't understand is if you're comparing an integer with another, why would it compare memory locations, or is this just for strings?
In case a
and b
are references, the ==
operator will compare "memory locations" since that is what the variables contain.
In case a
and b
are of primitive types, such as int
or double
the variables will contain actual values, consequently these values (and not their locations) will be compared.
(Note that a variable can never contain an object such as a String
, it can at most point at an object.)
Does that mean all integers with the value of 4 is stored in the same memory location?
No. As explained above, int
s are compared "directly". When it comes to Integer
the story is slightly different. First of all new
guarantees that you get hold of a fresh reference, that is
Object i = new Integer(5);
Object j = new Integer(5);
... i == j ...
will always yield false.
If you go through auto-boxing however:
Object i = (Integer) 5;
Object j = (Integer) 5;
... i == j ...
you'll get true due to the fact that auto-boxing goes through a cache for values in the range -128-127. (See for instance this question: Compare two Integer: why is == true?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With