Learner
Learner

Reputation: 544

Basic query regarding String

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.

Upvotes: 3

Views: 256

Answers (2)

Adam Stelmaszczyk
Adam Stelmaszczyk

Reputation: 19837

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.

Upvotes: 0

Manjunath
Manjunath

Reputation: 1685

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

Upvotes: 4

Related Questions