1

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 ?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.