aspose file tools*
The moose likes Java in General and the fly likes String pool and heap memory Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String pool and heap memory" Watch "String pool and heap memory" New topic
Author

String pool and heap memory

bjit babu
Greenhorn

Joined: Mar 25, 2010
Posts: 10
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

Joined: Oct 27, 2005
Posts: 19723
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
bjit babu
Greenhorn

Joined: Mar 25, 2010
Posts: 10
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
Bartender

Joined: Oct 14, 2005
Posts: 18675
    
    8

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

Joined: Mar 25, 2010
Posts: 10
So its basically we use a String pool for the performance of java engine.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14276
    
  21

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: String pool and heap memory