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.
The short answer is YES, they share the same memory address.
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.
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.
The heap is used for storing objects in memory.
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 :
new
keyword, they will never point to the same memory location. 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.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. 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)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