Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why System.out.println("hey s1==s2:"+s1==s2); prints "false" as the output instead of printing "hey s1==s2:false"

Tags:

java

string

I have written the following java code:

String s1 = new String("shan");
String s2 = new String("shan");
String s3="shan";
String s4="shan";
System.out.println("hey s1==s2:"+s1==s2);
System.out.println("s3==s4:"+s3==s4);
System.out.println("s1.equals(s2): "+s1.equals(s2));
System.out.println("s3.equals(s4): "+s3.equals(s4));
System.out.println("s1==s3: "+s1==s3);
System.out.println("s1.equals(s3): "+s1.equals(s3));
System.out.println("hey s1==s2:"+true);

The output:

false
false
s1.equals(s2): true
s3.equals(s4): true
false
s1.equals(s3): true
hey s1==s2:true

Why does line #5 result in just "false" as the output instead of "hey s1==s2:false"?

like image 894
owgitt Avatar asked Dec 06 '22 23:12

owgitt


2 Answers

Line5: System.out.println("hey s1==s2:"+s1==s2);

Because of the operator precedence "hey s1==s2:"+s1 resolving first and then comparing to s2 which leads to false.

Give the highest precedence to resolve it to correct. Parenthesis have the highest precedence.

System.out.println("hey s1==s2:"+(s1==s2));
like image 106
Suresh Atta Avatar answered Jan 10 '23 21:01

Suresh Atta


System.out.println("hey s1==s2:"+s1==s2)

evaluates ("hey s1==s2:"+s1)==s2, which is false

That's why false is printed.

The reason for this behavior is that the + operator has a higher precedence than the "==" operator.

The following would print what you expected :

System.out.println("hey s1==s2:"+(s1==s2))
like image 21
Eran Avatar answered Jan 10 '23 21:01

Eran