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 ?
Here's a modified version of your first expression, which prints 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.
So Java or any language has operator precedence, meaning some operations happen before others. 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
s5 == s3 checks if references are same are not.
s3 in created is string pool and s5 is new object and not referring to s3.
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.