Search This Blog

Wednesday, June 16, 2010

Differentiate the String Pool VS Heap Memory with HashMap

Differentiate the String Pool VS Heap Memory with HashMap::

This article about how to differentiate the String pool and Heap memory in Java.

One of my friend gave me a code and asked the output with explanation.

Code is:

package com.micro;

import java.util.HashMap;

public class StringPoolVSHeap {

public static void main(String arg[])

{

String stringPool=new String("2");

HashMap hashMap=new HashMap();

hashMap.put(new StringBuffer("1"),"One");

hashMap.put(new StringBuffer("2"), "two String Buffer");

hashMap.put(stringPool, "two String");

System.out.println("hashMap.get(new StringBuffer(\"2\"))::"+hashMap.get(new StringBuffer("2")));

System.out.println("hashMap.get(\"2\")::"+hashMap.get("2"));

}

}

i have told him answer in three sentence :
  1. HashMap always use hashCode as Key .

  2. What ever object is created with new keyword it will always created in Heap Memory . So its generate new hash code every time.


  1. As for as String concern it will be always crated in String Pool but before crating the string object in String pool it will check any other string contain same value in pool if it will existence than its will assign the old string object hashCode to the new String Object.



So output will be as follow::

hashMap.get(new StringBuffer("2"))::null

hashMap.get("2")::two String

check the same program with different probability.

If any one come across leave your valuable feed back.


1 comment: