Reputation: 146
String s = "abc";
String s4 = s + "";
System.out.println(s4 == s);
System.out.println(s4.equals(s));
This prints:
false
true
Can anybody please explain why is it so?
Upvotes: 1
Views: 72
Reputation: 36304
String s="abc"; // goes to string constants pool
String s4 = s +"" ;// has value "abc" but goes on heap and not in string constants pool
System.out.println(s4==s);//well,, the references are not equal. There are 2 diffrent instances with value="abc"
System.out.println(s4.equals(s)); // equals() checks for value and the values of both insatnces are equal.
Upvotes: 3
Reputation: 11163
Here is your code with output in comment -
String s="abc";
String s4 = s +"" ;
System.out.println(s4==s); //false
System.out.println(s4.equals(s)); //true
First one is false
because it is checking the reference of s4
and s
. Since these two reference are different it evaluated to false
. Here ==
(the equality) operator, when applied on reference type, is used to check whether two reference are same or different.
equals()
is a method which is achieved by every reference type from object class. You can override the equals() method for your own class.
The equals(s)
method is used to check whether the two object are meaningfully equals or not. For String
class the meaningfully equals means the two comparing strings are same but their references may be different. String
class has already override the equals()
method and hence you need not override the equals()
method by yourself.
Now for understanding string pool concept, consider the following code snippet -
String s5 = s;
System.out.println(s5); //abc
System.out.println(s5==s); //true
System.out.println(s5.equals(s)); //true
Here s5==s
evaluated to true. Because s5
is not referencing a new String object. It's referencing the the existing String object (that is - "abc" referenced by s
) in the string
pool. Now the both reference s5
and s4
are equals. In the last statement s5 and s are meaningfully equals and hence s5.equals(s)
evaluated to true
.
Hope it will help.
Thanks a lot.
Upvotes: 1