Memory location for the data members which is holding same value | Core Java Forum
V
Vikrant Posted on 14/07/2021

Hi,

Are we saving the data value in same memory or package when value of data member is exactly same ?


Y
Yogesh Chawla Replied on 15/07/2021

No.

If we create two objects using new keyword, they will never point to same memory location. This holds true for String objects as well meaning If we create two String objects using new, the two refers to the objects which point to two different memory locations.

String literals are a special case. A String literal is stored in the String literal pool so two String references to a String literal will always point to the same memory location.

There are other special cases in Java such as the Integer class. e.g
Integer a = 100; Integer b = 100; System.out.println(a==b); //This prints true

The output is true because Integer values between -128 and 127 are cached by the JVM(and cached by all JVM implementations. It is upto individual's JVM implementation to cache values beyond this range).