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, whereasnew 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:
==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 timeequalsneed to be used instead.