Given this example code:
class basic {
public static void main(String[] args) {
String s1 = "Java";
String s2 = new String("Java");
}
}
Are s1
and s2
both reference variables of an object?
Do those two lines of code do the same thing?
Lines 3, 4 don't do the same thing, as:
String s1 = "Java";
may reuse an instance from the string constant pool if one is available, whereas new String("Java");
creates a new and referentially distinct instance of a String object.
Therefore, Lines 3 and 4 don't do the same thing.
Now, lets have a look at the following code:
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2); // true
s2 = new String("Java");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
==
on two reference types is a reference identity comparison. Two objects that are equals are not necessarily ==
. Usually, it is wrong to use ==
on reference types, and most of the time equals
need to be used instead.