String equals and == with String concatenation [duplicate]

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));

Leave a Comment