• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String literal pool working

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 2236
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic