Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String pool and heap memory

 
bjit babu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

here i have a confusion about String instantiation .

Let suppose I have a code fragment like bellow


String str="abc";

String str1="abc";

String st=new String("abc");


when I use a == operator for str and str1(str==str1) String object I will get true. Which means both the reference pointing to a same String object.

But when I use a == operator between str and st (str==st) then it will come as false (in spite there hash code being same . ) which means they are pointing to different object
which should not be as far as String pool is concerned. So is the third object is going to the heap rather than a String pool.

please help me regarding this String pool and heap concept.

Thanks
Biswajit

 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every time you use the new keyword an object is created inside the heap, even for Strings. The String pool is only used for String literals ("xxx") and when you call intern() on a String.
 
bjit babu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I got the point .but what is the point of having pool. basically why we need a sting pool when a String can a take place in heap.


Thanks
Biswajit.
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's so you can use a String literal as often as you like in your code, but only one instance of it is stored in memory.
 
bjit babu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So its basically we use a String pool for the performance of java engine.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you write code like this:

then it makes no sense for Java to make four different String objects. Strings are immutable (the content of a String object cannot be changed after it has been created). So, to save memory, Java will create just one String object, in the string pool, and it will reuse it whenever you use the same string literal. In the example above, all four variables will refer to the same String object.

The purpose of the string pool is to make it possible to do this sharing. It's a memory usage optimization.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic