I am trying to understand the String concatenation with the output of String compare. To be clear, i have the class to compare two strings using == and equals. I am trying to concat the output of == and equals() to a string. The output of equals() concats, but the output of == does not concat. Using boxing feature of java, the boolean concatenated with string will contact. Both equals and == returns boolean to my knowledge. So why is this difference? Can anyone explain on this?
public class StringHandler {
public void compareStrings() {
String s1 = new String("jai");
String s2 = "jai";
String s3 = "jai";
System.out.println("Object and literal compare by double equal to :: "
+ s1 == s2);
System.out.println("Object and literal compare by equals :: "
+ s1.equals(s2));
System.out
.println("Literal comparing by double equal to :: " + s2 == s3);
System.out.println("Literal comparing by equals :: " + s2.equals(s3));
}
public static void main(String[] args) {
StringHandler sHandler = new StringHandler();
sHandler.compareStrings();
}
}
output
false
Object and literal compare by equals :: true
false
Literal compareing by equals :: true
Update: Answer
Without parenthesis for s1==s2, the JVM compares the string as "Object and literal compare by double equal to :: jai" == "jai" and the result is false. So the actual content in sysout is not printed. When parenthesis is added the JVM compares the string as "jai" == "jai" and the result is
Object and literal compare by double equal to :: true