0
public class MyString {
    public static void main(java.lang.String[] args){
        String a="Hello";
        a=a.trim().concat("World");
        String c="HelloWorld";
        System.out.println(a==c);//returns false
    }

interning should happen implicitly for string literals .Then why a and c are treated as two different strings? Will a and c point to same memory reference in string pool? Hash code returned by a and c are same but a==c returned false. Can someone explain on why the value returned is false.

  • 2
    A similair [question](https://stackoverflow.com/questions/51036434/will-b-and-c-have-same-memory-reference-in-string-pool) was asked a while ago. – soufrk Jun 26 '18 at 07:21
  • 2
    `concat()` does **not** add the returned `String` to the String pool. – Eran Jun 26 '18 at 07:21

2 Answers2

1

interning should happen implicitly for string literals

It does.

Then why a and c are treated as two different strings

Because they are two different String instances, that happen to have the same content. a's value isn't a string literal.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

The method concat doesn't add the new created string to the internal of strings. Here is the implementation of concat:

public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}

That follow also is documented in JLS:

Strings computed by concatenation at run time are newly created and therefore distinct.

It means that when the code executes String c="HelloWorld";a new String is created and added to the intern because the previous HelloWorld was not present in intern.

The two strings differs by location (reference) so checking them with == returns false.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56