user2990622
user2990622

Reputation: 11

String boolean confusion

I was doing a practice Computer science test and tried this question out.

String sam = "scary";
String ben = new String("scary");
String wil = "scary";
out.print( sam == ben );
out.print( " " + (sam == wil) );

From my knowledge I thought the printouts would be false false because from what I know, strings can only be compared with .equals(). But I got it wrong. It says that the answer was false true. Can someone please explain why?

Upvotes: 0

Views: 79

Answers (2)

SteveL
SteveL

Reputation: 3389

When you create Strings without the new word the jre searches in a pool of Strings that you created before for a String that has the same content ,if it finds one then there is no need to create a new String in the memory and just refferences the new String to the one you created before. In the other hand by using the new keyword you are forcing to create a new Object.

Upvotes: 0

NPE
NPE

Reputation: 500267

You can compare strings with ==. However, that compares string references rather than the character sequences.

If the two character sequences are different, == will always evaluate to false. If they are the same, == may return true or may return false; this depends on how the two string objects came into existence.

The reason sam and wil refer to the same object is spelled out in JLS §3.10.5 String Literals:

String literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

See Example 3.10.5-1 in the JLS for a detailed illustration of this behaviour.

Upvotes: 4

Related Questions