Ramblings from a Bihari!

Just another WordPress.com weblog

Interesting inconsistency with java String pool

I was just trying out the intern() method of java.lang.String class and found an interesting issue.

The intern() method is supposed to put the string literal in the intern pool and give you back a handle to that.

Let me explain the scenario with two programs:-

public static void main(String[] args) {

char[] c = new char[]{‘a’,’b’,’c’};
String s = new String(c).intern();
System.out.println(System.identityHashCode(s));
s = null;
for (int i = 0; i < 20; i++) {
System.gc();
}
String s1 = new String(c).intern();
System.out.println(System.identityHashCode(s1));

}

What are the two values this program is supposed to print ?? I think since the intern is an WeakHashMap so after the gc call it should print two different values of identityHashCode.  Yes till now we are correct theortically and practically both.  But  if you replace the character array with any of

1. new char[]{‘a’,’b’,’c’};

2. new char[]{‘a’,’b’};

3. new char[]{‘a’};

The program will print both the hashcode values as same. Thats strange and very inconsistent. As per my understanding  the value of elements in the array should not be responsible for the behavior of intern() or any other java method.

Advertisements

July 31, 2008 - Posted by | techie stuff

1 Comment »

  1. I believe s1 and s will return same hashcode. Since the string new char[]{‘a’,’b’,’c’} will be present in the string pool. Also System,gc() will not remove the string from the pool, so the same object will be referred.
    Documentation says”

    Comment by Harshit | May 25, 2010 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: