String equals and == with String concatenation [duplicate]
Solution 1:
When you do
System.out.println("Object and literal compare by double equal to :: "
+ s1 == s2);
you are first concatenating the string "Object and literal compare by double equal to :: "
with the string s1
, which will give
"Object and literal compare by double equal to :: jai"
then, you are checking if this string is the same object (same reference) than s2
:
"Object and literal compare by double equal to :: jai" == "jai"
which will be false
(the output will be false
).
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:
System.out.println("Object and literal compare by double equal to :: " + (s1 == s2));
Solution 2:
Add parentheses!
System.out.println("Object and literal compare by double equal to :: " +
(s1 == s2));
PLus and other arithmetic ops have higher priority than comparison ops. Using '+' for concat doesn't change that.
Solution 3:
problem:
+ s2 == s3
+
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:
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 compareing by double equal to :: " + (s2 == s3));
System.out.println("Literal compareing by equals :: " + (s2.equals(s3)));
operator precedence: