Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java == behaving ambiguously

Tags:

java

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
like image 597
Anirban Nag 'tintinmj' Avatar asked Nov 18 '13 18:11

Anirban Nag 'tintinmj'


3 Answers

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/

like image 100
Deadron Avatar answered Oct 03 '22 09:10

Deadron


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".

like image 22
rgettman Avatar answered Oct 03 '22 09:10

rgettman


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
like image 33
Anirban Nag 'tintinmj' Avatar answered Oct 03 '22 09:10

Anirban Nag 'tintinmj'