How many memory locations will it take to have a string concatenation?

java, memory-management, string, stringbuilder

Solution

First statement will be converted by compiler into `String s = "ABCDEF";` so there will be no concatination

Second statement will be converted by compiler into this code (or something like this)

    String s = "ABC";
    StringBuilder sb = new StringBuilder(s);
    sb.append("DEF");
    s = sb.toString();

Problem

How many memory locations will it take to have a string concatenation? ``` String myStringVariable = "Hello"; ``` In following two statements : ``` String s = "ABC" + "Hello" + "DEF"; ``` and ``` String s = "ABC"; s = s + "Hello"; s = s + "DEF"; ``` and ``` String s = "ABC" + myStringVariable + "DEF"; ``` Which will consume more memory? In which of the case StringBuilder is useful to the most?

Original source