String is a class in Java different from other programming languages. So as for every class the object declaration and initialization is
String st1 = new String();
or
String st2 = new String("Hello");
String st3 = new String("Hello");
Here, st1
, st2
and st3
are different objects.
That is:
st1 == st2 // false
st1 == st3 // false
st2 == st3 // false
Because st1
, st2
, st3
are referencing 3 different objects, and ==
checks for the equality in memory location, hence the result.
But:
st1.equals(st2) // false
st2.equals(st3) // true
Here .equals()
method checks for the content, and the content of st1 = ""
, st2 = "hello"
and st3 = "hello"
. Hence the result.
And in the case of the String declaration
String st = "hello";
Here, intern()
method of String
class is called, and checks if "hello"
is in intern pool, and if not, it is added to intern pool, and if "hello" exist in intern pool, then st
will point to the memory of the existing "hello"
.
So in case of:
String st3 = "hello";
String st4 = "hello";
Here:
st3 == st4 // true
Because st3
and st4
pointing to same memory address.
Also:
st3.equals(st4); // true as usual