0

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?

3
  • 1
    What language is this? Commented Nov 14, 2013 at 20:38
  • So add the [java] tag to your question next time @user2990622 Commented Nov 14, 2013 at 20:40
  • String interning is the reason: en.wikipedia.org/wiki/String_interning Commented Nov 14, 2013 at 20:45

2 Answers 2

4

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.

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

Comments

0

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.

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.