3

This is a very basic question regarding String.

String str1 = "abc";
String str2 = "abc";

System.out.println("out put " + str1 == str2);

I was shocked when I executed the program. I got false.

According to me, string literals are shared between the String references if another string wants to point to the same String literal. JVM will check it in String pool first and if it is not there then it will create one and give the reference, otherwise it will be shared between multiple String references like in this case (according to me).

So if I go by my theory then it should have been returning true as both the String reference point to same String literal.

2
  • 3
    @broncoAbierto That's not the same question. The OP seems to understand reference comparisons well enough, and intended to test constant string interning. The issue was operator precedence. Commented Sep 13, 2014 at 9:24
  • @kiheru You're right. I take back my comment. Commented Sep 13, 2014 at 9:28

2 Answers 2

4

You need to do the following to check it correctly:-

System.out.println("out put " + (str1 == str2));

This will give you true as expected.

Your statement does "out put" + str1 and then tries to equate it with str2

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

Comments

0

You're right about the String behaviour. But, you forgot about operator precedence. First addition is executed, later equality.

So, in your case, firstly "out put " + str1 is executed, which gives "out put abc". Later this is compared to str2, which gives false.

You meant "out put " + (str1 == str2), which indeed gives true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.