Search code examples
javamemorygarbage

Do two objects of a class refer to the same memory location?


I am starting to learn some Java and I have been reading a lot about how memory is allocated by the JVM and consequently how this memory is freed using the garbage collector.

One thing that I have been unable to find out is if I create two new objects which are exactly the same would they refer to the same location in memory? Similar to how the String Pool works.


Solution

  • One thing that I have been unable to find out is if I create two new objects which are exactly the same would they refer to the same location in memory? Similar to how the String Pool works

    The answer is No :

    1. If you create two objects using the new keyword, they will never point to the same memory location.
    2. This holds true for String objects as well. if you create two String objects using new, the two references to these objects will point to two different memory locations.
    3. 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.
    4. 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 because Integer values between -128 and 127 are cached by the JVM. (The values between -128 and 127 are cached by all JVM implementations. It is upto the individual JVM implementation to cache values beyond this range)