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.