This is because in case of String newStr = "" + 'g' + 'o' + 'o' + 'd'; you are forming the new string with compile time constant expression. So the resulting string will automatically be interned by the JVM, which means it will assign the same String object that the JVM created earlier.
In the question, the new string is computed by a loop. Loop is not a constant expression. It is computed at run time and so the JVM returns a new un-interned String object.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
I do not understand when the String pool is or isn't used. Why isn't an existing String in the String pool found and used at run time? Wouldn't part of the benefit of having a String pool include making use of it at run time?
Basically, the String pool is used whenever you have a String whose value is know at compile time. The exact details are given in Section 3.10.5 of JLS.
Can't really comment on why it is done that way. In designing a language some things are done a certain way not because they are right or wrong but because the designers believe that that is more practical or useful based on their experience. There are pluses and minuses of each approach and they have to strike a good balance.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
Why doesn´t in the last loop the String resulted from "newStr + ch;" come from String Pool? I mean, in the last iteration of such loop there is the string "good" which can be found in String Pool? I read all comments above and I don´t understand why "In every iteration of the loop, a new String object is created by appending the character to the existing String object". It makes sense that "g", "go", "goo" are created but why "good" isn't just used from String Pool? Should I assume that whenever a String is used in a loop it will not be used from String Pool? Or should I assume that whenever the String is resulted from concatenation (i.e newStr + ch) will never be used from String Pool?
A String from the string pool will be used if it is computed at compile time, or, are constants. In this case, a string is being computed at runtime and so, it cannot be interned automatically. You would have to call the intern() method on that string to get the string object from the string pool
I understood from "it cannot be interned automatically" that the only way to put a string in String pool after the rpogram starts is by calling intern method, right?