Reputation: 83
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.
Upvotes: 8
Views: 7680
Reputation: 15212
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)Upvotes: 12
Reputation: 100139
If you create the new object using the new
operator, it's guaranteed to be the new object distinct from any other objects existed before. However when you create objects in indirect way (for example, using factory methods), the object existed before may be reused. A good example is Integer.valueOf(int)
method which caches small numbers and returns the same instance:
Integer a = Integer.valueOf(10);
Integer b = Integer.valueOf(10);
// a and b is the same object
Integer c = new Integer(10);
Integer d = new Integer(10);
// c and d are two distinct objects
Note that even if JVM can determine that two new objects are essentially the same, it simply cannot merge them to the single object, because it would violate the language specification and may break your program later. For example, you may decide to synchronize on both of these objects later. According to the specification these synchronizations should not interfere, but if JVM merges these two objects, synchronization on the first one will have to wait for the synchronization on the second one.
Upvotes: 3
Reputation: 20185
No, they are not the same object. You can verify this with the ==
operation which checks, whether two references refer to the same object.
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);
This will print false
, which is the exact reason why you normally never want to compare String
s (or really, any object) with ==
(ref this post). The correct way to check for (content) equality is equals(Object that)
.
Upvotes: -1