4

I was testing around Strings, and I came up with below code:

public static void main(String[] args){
    StringBuilder sb1 = new StringBuilder("Cuba");
    String str1 = sb1.toString();
    // n1
    System.out.println(str1 == str2);
}

On n1 if I place:

String str2 = sb1.toString();

I get false. However if I place:

String str2 = str1;

I get true.

I am not sure why this is happening: both codes are referring to the same instance, therefore, both output must be true.

Any idea why both output differ? I know how to compare Strings, I am just curious about the reason why the result differ.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Cuban coffee
  • 294
  • 5
  • 14

1 Answers1

6

This is the code of StringBuilder.toString() in OpenJDK 8u40:

@Override
public String toString() {
    // Create a copy, don't share the array
    return new String(value, 0, count);
}

so it's returning a new String everytime you invoke it.

When you set str2 = str1, they are the same instance so == returns true. However, when you set str2 = sb1.toString(), it gets set to a new String (having the same content), so == returns false.

This is actually specified in toString() Javadoc (emphasis mine):

Returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.

Note that you shouldn't be using == to compare Strings to begin with (refer to this question).

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423