It is not that difficult. If you are talking about Strings -)
First, let's ignore strings and accept this simple type:
public class ValueHolder { private final int value; public ValueHolder(int value) { this.value = value; } public int getValue() { return value; } }
If you have two lines:
ValueHolder vh1 = new ValueHolder(1); ValueHolder vh2 = new ValueHolder(1);
then you create exactly 2 objects on the heap. Despite the fact that they behave in exactly the same way and have the same values โโstored in them (and cannot be changed), you will have two objects.
So vh1 == vh2 will return false !
The same is true for String objects: there can be two String objects with the same value.
However , there is one peculiarity in String : if you use <24> (*) , ( , ).
So, in your example, the code str1 and str2 will point to the same object .
(*) or more precisely: a expression of a compile time constant of type String .
source share