[英]java string concat strange behavior
I am getting strange string concat behavior, please help me understand this behavior .我遇到了奇怪的字符串连接行为,请帮助我理解这种行为。
String s3 = "ABC";
String s5 = new String(s3);
System.out.println("s5 == s3 "+ s5 == s3); // output: false
System.out.println("s5 == s3 "+ (s5 == s3)); // output: s5 == s3 false
Should first print s5 == s3 false instead of false ?应该先打印s5 == s3 false而不是false ?
Here's a modified version of your first expression, which prints false
:这是您的第一个表达式的修改版本,它打印
false
:
System.out.println(("s5 == s3 " + s5) == s3); // "s5 == s3 ABC" == "ABC"
==
has lower precedence than +
, so concatenation is done first, then comparison follows. ==
优先级低于+
,因此先进行连接,然后进行比较。
To make it produce your expected output, you need to override this operator precedence, just as you did in your second sysout
, which will concatenate the result of the comparison to the string.要使其产生预期的输出,您需要覆盖此运算符优先级,就像您在第二个
sysout
所做的那样,它将比较的结果连接到字符串。
So Java or any language has operator precedence, meaning some operations happen before others.因此 Java 或任何语言都具有运算符优先级,这意味着某些操作先于其他操作发生。 In the first line, the "==" has a lower precedence (happens later) than "+", which happens earlier, so the output is the result of the "==" operation, which is false
在第一行中,“==”的优先级低于“+”,后者发生得更早,所以输出是“==”操作的结果,它是假的
see more on operator precedence here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html在此处查看有关运算符优先级的更多信息: https : //docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
s5 == s3 checks if references are same are not. s5 == s3 检查引用是否相同。
s3 in created is string pool and s5 is new object and not referring to s3. created 中的 s3 是字符串池,s5 是新对象,而不是指 s3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.