This question already has an answer here:
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
Add parentheses!
PLus and other arithmetic ops have higher priority than comparison ops. Using '+' for concat doesn't change that.
When you do
you are first concatenating the string
"Object and literal compare by double equal to :: "
with the strings1
, which will givethen, you are checking if this string is the same object (same reference) than
s2
:which will be
false
(the output will befalse
).In other words, it's because operators precedence. One way to "manipulate" operators precedende is to use parentheses. The operations inside parentheses will be parsed first:
problem:
+
sign has higher precedence than==
so it will execute(append
) it first before executing the==
thus giving you only"false"
You need to put parenthesis so it will check for the result of your string compare.
also
parenthesis
has higher precedence than+
sign to it will compare the string first before appending it to the string.sample:
operator precedence:
This is an order of operations issue. It's being interpreted as follows (parentheses added) :