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