Search code examples
javaequals-operator

When am comparing objects through == operator java sop command not printed appended text why?


My code below

public class EqualsComMetod_Operator {

  public static void main(String[] args) {

    String s1=new String("Raja");
    String s2=new String("Raja");
    System.out.println("s1==s2::"+s1==s2);
    // Here the text s1==s2:: not printed on my console why??
  }
}

Output:

false

Am comparing the objects as reference/address and try to print like this:

s1==s2::false

but directly showing false. Why?


Solution

  • The operator + is evaluated before the ==.

    So if you examine the expression "s1==s2::"+s1==s2:

    First "s1==s2::"+s1 is evaluated. It results in "s1==s2::Raja". Then, "s1==s2::Raja"==s2 is evaluated, and obviously results in false.

    You can control the precedence using brackets:

    public static void main(String[] args) {
        String s1 = new String("Raja");
        String s2 = new String("Raja");
        System.out.println("s1==s2::" + (s1 == s2));
    }