• Post Reply Bookmark Topic Watch Topic
  • New Topic

String literal pool working  RSS feed

 
Jomy George
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone clear some doubts on String literal pool working.
I think when a JVM loads a class, it will search for all String literals in it, and store it in pool (will check existence of same value in pool first).
But if we write like

String s1 = new String("abc"); or
StringBuffer sb1 = new StringBuffer("def")

both "abc", and "def" will be saved in heap (not in pool).

I doubt what will happen if we have a code like this

s1= s1.append("xyz");, will "xyz" get saved in literal pool?
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jomy George wrote:But if we write like

String s1 = new String("abc"); or
StringBuffer sb1 = new StringBuffer("def")

both "abc", and "def" will be saved in heap (not in pool).


That's tricky. The result of this expression new String("abc"); will be saved into the heap.
However the literal itself (the parameter passed to the constructor) will be saved in the String pool.
 
Jomy George
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Pawel.

So if we have a like String s1 = new String("abc"), i guess following actions happens.

1. "abc" get saved in pool
2. "abc" get saved in heap
3. variable s1 get saved in stack which holds a reference to "abc" in heap.

Am i correct?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!