Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How strings are handled in java

Tags:

java

string

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?

like image 548
Divya Rose Avatar asked Jun 15 '15 10:06

Divya Rose


2 Answers

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.

like image 137
aioobe Avatar answered Oct 22 '22 11:10

aioobe


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.

like image 20
Konstantin Yovkov Avatar answered Oct 22 '22 12:10

Konstantin Yovkov