The ==
operator will check for reference equality, that is, will return true
if the two argument String
s are the same instance.
Whenever a String
literal (for instance "Hello"
) occurs in a class, a String
instance is interned (kind of stored in an internal cache so it can be reused).
After doing String txt1="Hello"
, txt1
will be very same reference of the interned String
. So,
String txt1="Hello";
String txt2="Hello";
Results in txt1
and txt2
being the same instance, that is, the interned one.
When you're doing String txt1=new String("Hello")
, it's calling the String
constructor with the interned instance as an argument (kind of a copy constructor). So, txt1
will be a new String
instance holding the same value as the interned instance, and the ==
operator will return false
.
More information on the subject can be found in the 3.10.5. String Literals section of the JLS.
A string literal is a reference to an instance of class String
(§4.3.1, §4.3.3).
Moreover, a string literal always refers to the same instance of class
String. This is because string literals - or, more generally, strings
that are the values of constant expressions (§15.28) - are "interned"
so as to share unique instances, using the method String.intern.
The following question's answer explain When are Java Strings interned?. The following link elaborates on the subject: String Equality and Interning.
As a side note, remember to use equals()
in order to perform String comparisons based on their contents.