In s2
there will be only one object created, in the string pool.
Actually no, this line will create no new objects. s2
will be a reference to the same constant used to construct s1
.
There are now 3 objects in string pool ("abc"
, "def"
, and "abcdef"
), two are abandoned ("def"
and "abcdef"
) leaving "abc"
in memory.
No, only "abc"
and "def"
are in the constant pool, and since they are constants they will remain in memory for the duration of the program. "abcdef"
will be garbage collected promptly after it is constructed since it is never stored anywhere.
Had you used the +
operator instead of String.concat()
the compiler would in fact merge two constant strings into one, and only store the resulting string in the pool.
Both references are referencing a string pool object.
No, only s2
references a string in the constants pool, and neither result of .concat()
will be in the constants pool.
What's the significance of memory object?
Are you asking what the point of the string constants pool is? It's essentially just an optimization to allow constants (i.e. "
-ed strings in your code) to share the same reference to avoid constructing numerous identical instances. Because they're constants, this can be done at compile-time, saving both space and time at runtime. This does not apply to any strings constructed at runtime unless you explicitly call .intern()
, however you should generally avoid doing so.
You may also be interested in Where does Java's String constant pool live, the heap or the stack?
Edit: since you're insisting that "abcdef"
in your example will be part of the constants pool, here's simple proof that is not the case:
$ javac -version
javac 1.7.0_02
$ cat Test.java
public class Test {
public static void main(String[] args) {
String s1 = "123" + "456";
String s2 = "abc".concat("def");
}
}
$ javac Test.java
$ javap -c -classpath . Test
Compiled from "Test.java"
public class Test {
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2 // String 123456
2: astore_1
3: ldc #3 // String abc
5: ldc #4 // String def
7: invokevirtual #5 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
10: astore_2
11: return
}
As you can clearly see, the strings 123456
, abc
, and def
are constants (see ldc
), and String.concat()
is called at runtime.