Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
Anon87489384 Avatar asked Jun 28 '15 09:06

Anon87489384


People also ask

Do objects share same memory?

The short answer is YES, they share the same memory address.

Can two objects have same reference?

Is it possible for two object names references to point to the same object (i.e. piece of memory) ? Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.

Where is object of a class is stored in memory?

There are two parts of memory in which an object can be stored: stack – Memory from the stack is used by all the members which are declared inside blocks/functions. Note that the main is also a function. heap – This memory is unused and can be used to dynamically allocate the memory at runtime.

Where objects are stored in memory?

The heap is used for storing objects in memory.


1 Answers

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)
like image 190
Chetan Kinger Avatar answered Sep 21 '22 09:09

Chetan Kinger