I have two questions:
public static void main(String[] args) {
String s1 = \"bla\";
String s2 = \"b\" +\"l\" + \"a\";
String s3 = \"b\".concat(\"l\").c
Why does s1 and s2 point to the same object, whereas s1 and s3 doesn't? (There is no usage of new keyword).
Since String
in Java are Immutable
, so any method of string class will return a new String object (there are some exception though - one is substring
method). Hence concat
method creates a new string, that goes to the Heap, and is not added to constant pool.
As far as the case of s1
and s2
is concerned, both strings are known at compile time, and hence they are same string literals.
Note that the concatenation operation in 2nd string: -
String s2 = "b" +"l" + "a";
is evaluated at compile time, and the result is known to be same as the first string, and one entry is made to the constant pool.