String a = "abc";
This creates literal "abc"
in string pool.
String b = "abc";
No new literal is created. b
is pointed to the existing "abc"
.
String c = new String("abc");
Now the object is created in heap and c
is pointed to the heap. The literal is also created in the string pool.
But, what happens if the pool already has the literal "abc"
? Will there be duplicate literals in the pool?
But, what happens if the pool already has the literal "abc"? Will there be duplicate literals in the pool?
No.
String c = new String("abc");
is semantically equivalent to
String tmp = "abc";
String c = new String(tmp);
By this it should be clear that no extra entry in the string pool is created just because the literal is used as argument to the string constructor.
You are right about the fact that new String(...)
creates a string on the heap, so looking at both heap and string pool, there will be multiple objects representing "abc"
, but no more than one in the string pool.
[...] That is when we use string literals. But will the literal in the string pool be reused if we give,
String a = new String("abc");
?
Yes, the string pool literal will be reused if you give "abc" as argument to the constructor. The resulting String object will however not be in the pool, but on the heap.
But, what happens if the pool already has the literal "abc"?
It will simply be reused.
If you somewhere do String x = "abc";
and somewhere else String y = "abc";
then x == y
will always be true
. This proves that actually the literal is re-used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With