简体   繁体   中英

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

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

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

To comapre strings you have to call s1.equals(s2) . the result is true . == compares the pointer to the strings and that sare not the same.

use brackets for surround separate operations in statement.

use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM