Basic String Query

This is a very simple question about String.

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

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

      

I was shocked when I completed the program. I got it false

.

According to me, string literals are split between String references in case another string wants to specify the same string literal. The JVM will first check it in the string pool, and if it doesn't have one, it will create it and provide a link, otherwise it will be passed between multiple string references like in this case (for me).

So if I go my theory then it should have returned true

as a String reference in the same string literal.

+3


source to share


2 answers


For a correct check, you need to do the following: -

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

      



This will give you the true value as expected.

Your expression does "out put" + str1 and then tries to match it against str2

+4


source


You are correct about String behavior. But you forgot about operator precedence. Complement first, equality later.

So, in your case, the first "out put " + str1

thing to do is that gives "out put abc"

. This is later compared to str2

that gives false

.



You mean "out put " + (str1 == str2)

, which really gives true

.

0


source







All Articles