It's not so complicated. Except if you're talking about Strings ;-)
First, let's ignore Strings and assume 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 like this:
ValueHolder vh1 = new ValueHolder(1);
ValueHolder vh2 = new ValueHolder(1);
then you'll have created exactly 2 objects on the heap. Even though they behave exactly the same and have the exact same values stored in them (and can't be modified), you will have two objects.
So vh1 == vh2
will return false
!
The same is true for String
objects: two String
objects with the same value can exist.
However, there is one specific thing about String
: if you use a String
literal(*) in your code, Java will try to re-use any earlier occurance of this (via a process called interning).
So in your example code str1
and str2
will point to the same object.
(*) or more precisely: a compile-time constant expression of type String
.