[英]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: 我写了以下java代码:
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"? 为什么第5行导致输出只是“假”而不是“hey s1 == s2:false”?
System.out.println("hey s1==s2:"+s1==s2)
evaluates ("hey s1==s2:"+s1)==s2
, which is false
评估("hey s1==s2:"+s1)==s2
,这是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. 由于运算符优先级"hey s1==s2:"+s1
首先解析然后与s2比较导致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)
. 要comapre字符串,你必须调用s1.equals(s2)
。 the result is true
. 结果是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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.