I came across this question in a Facebook group. I know I should be using equals() method but I want to know why this is happening
class Main
{
public static void main (String[] args)
{
String s1="abc:5";
String s2="abc:5";
System.out.println(s1==s2);
System.out.println("s1 == s2 " + s1==s2);
}
}
OUTPUT
true
false
This is due to operator precedence. '+' has a higher precedence than ==. You are actually comparing ("s1 == s2" + s1) to s2.
http://introcs.cs.princeton.edu/java/11precedence/
The confusion is in the order of operations. What is happening is that you're concatenating "s1 == s2 " and s1, then using == on that result and s2.
They are different objects, so false is printed (and "s1 == s2" is not printed). Put parentheses:
System.out.println("s1 == s2 " + (s1==s2));
This will print s1 == s2 true because both s1 and s2 refer to the same interned string literal, "abc:5".
Oh I just make some change in the code and get that + first doing "s1 == s2 s1" then == with s2 which is not true. New code
class Main
{
public static void main (String[] args)
{
String s1="abc:5";
String s2="abc:5";
System.out.println(s1==s2);
System.out.println("s1 == s2 " + (s1==s2));
System.out.println("s1 == s2 " + s1==s2);
}
}
OUTPUT
true
s1 == s2 true
false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With