If String
s are immutable in Java, then how can we write as:
String s = new String();
s = s + \"abc\";
String s = new String();
An empty String
object (""
) is created. And the variable s
refers to that object.
s = s + "abc";
"abc"
is a string literal (which is nothing but a String
object, which is implicitly created and kept in a pool of strings) so that it can be reused (since strings are immutable and thus are constant). But when you do new String()
is totally different because you are explicitly creating the object so does not end up in the pool. You can throw is in the pool by something called interning.
So, s + "abc"
since at this point concatenation of and empty string (""
) and "abc"
does not really create a new String
object because the end result is "abc"
which is already in the pool. So, finally the variable s
will refer to the literal "abc"
in the pool.