Sponsored Links

Ad by Google
In our previous post we have discussed about Why String is Immutable here and few popular immutable classes. In this post we are going to discuss What is String pool and also run an example. String pool is of course popular in java interview questions, sometimes interviewer asked you to compare two String, and when you start comparing using == operator String pool discussion begins.

What is String Pool?

String pool is special storage area inside heap memory, to store only one copy of distinct String value, which must be immutable. String pool ensure you the memory usage by keeping the String object into a pool, so that already created string object can be re-use by multiple instances instead of creating a new one. String pool makes your string processing more time and space efficiency. String pool implementation is based on one of the very popular design pattern known as Flyweight Design Pattern.
Let's see the theoretical example.
String softDrink = "Pepsi";
String mySoftDrink = "Pepsi";

We have two variable softDrink and mySoftDrink both have the same value as "Pepsi", There will be only one object created inside the String Pool. What happens internally, whenever any String object is created, It will first trying to find the value of string inside the String pool, and if found returned the reference of that string from the pool instead of creating a new object. So in our case softDrink = "Pepsi" will goes inside the String pool and for mySoftDrink the reference of "Pepsi" will return instead of creating a new "Pepsi" object. See an image of String Constant Pool for both variables.

In java there are two ways to create String object,
String str = new String("YourString");// This goes to heap memory
String str2 = "YourString"; // This will inside string pool

Of course you can push the String object created using new operator to placed in side String pool using String.intern() method let's see an code example.
package com.javamakeuse.poc;

public class StringPoolEx {

 public static void main(String[] args) {
  String str = "Pepsi"; // goes inside pool
  String str2 = "Pepsi"; // return reference from the pool
  String str3 = new String("Pepsi"); // goes inside heap
  String str4 = new String("Pepsi").intern(); // return from the pool

  System.out.println(str == str2); // print true
  System.out.println(str2 == str3); // print false
  System.out.println(str2 == str4); // print true

Here are few popular java interview questions:
Which Collection is better to store 10 millions of records between ArrayList and LinkedList Here
What are the key differences between Comparator and Comparable - Here
Design your own ArrayList - Here
Serializable Vs Externalizable - Here

Friends if I missed something about String pool, of course you can share that point with me, I will update that point to this post.
Sponsored Links


Post a Comment