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.
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)