Search code examples
javastringmutable

Appending the string


Can anyone please explain what is the difference between below implementation of String-

1)

{
    String comma=",";
    return finalStr = "Hello"+comma+"Welcome"+comma+"to"+comma+"Stack"+comma+"overflow";
}

2)

{
    return finalStr = "Hello,Welcome,to,Stack,overflow";
}

How many string object will be created in first (1) block, will there be only one string finalStr which refer to memory location where Hello,Welcome,to,Stack,overflow is stored or will it create multiple locations for each word and then once appended it will create a new memory location.


Solution

  • In both cases, only one String object will be created for each. Since, compiler is smart enough for understand the concatenation in compile time. These are string literals, they will be evaluated at compile time and only one string will be created for each cases.

    As per JLS

    A long string literal can always be broken up into shorter pieces and written as a (possibly parenthesized) expression using the string concatenation operator + [...] Moreover, a string literal always refers to the same instance of class String.

    • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
    • Strings computed by concatenation at run-time are newly created and therefore distinct.