Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does == compare memory location?

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?

like image 875
liloka Avatar asked Nov 29 '22 03:11

liloka


1 Answers

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, ints 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?)

like image 62
aioobe Avatar answered Dec 05 '22 05:12

aioobe