Different outputs when calling toString in a single StringBuilder instance

I tested the lines and I came up with the code below:

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

In n1if I put:

String str2 = sb1.toString();

I get it false. However, if I put:

String str2 = str1;

I get it true.

I'm not sure why this happens: both codes refer to the same instance, so both outputs should be true.

Any idea why both outputs are different? I know how to compare strings, I'm just wondering why the result is different.

+4
source share
1 answer

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

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

so that it returns a new line every time you call it.

str2 = str1, , == true. , str2 = sb1.toString(), ( ), == false.

toString() Javadoc ( ):

, . String , , . . .

, == String (. ).

+6

Source: https://habr.com/ru/post/1618745/


All Articles