File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

String pool and heap memory

bjit babu

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.


Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

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.

How To Ask Questions How To Answer Questions
bjit babu

Joined: Mar 25, 2010
Posts: 10

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.

Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

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

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: 15084

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
I agree. Here's the link:
subject: String pool and heap memory
It's not a secret anymore!