Archive for String

String constant pool

Posted in Programming with tags , , on November 26, 2006 by wsjoung

Everybody knows about String constant pool which is for efficient memory management in java. Basically most of objects are managed on heap area but String object. In most of ordinary application, programmers use String object quite often and this String object quite frequently need to be changed or it occupies large amounts of memory. Therefore instead of managing String object on heap area, they introduced String constant pool.

One of important characteristic of String constant pool is that it doesn’t create same String object if there is already String constant in the pool.

String var1 = “This is String Literal”;
String var2 = “This is String Literal”;

For above two String objects, JVM creates only one object in the String constant pool and for the second string reference variable (var2), it points the string object which is created for var1. In this case, (var1 == var2) is true.

But one thing, people make confused is that. It works only when it encounter on String Literal with double quote.

String var3 = new String(“This is String Literal”);

In this case, a regular object will be created by new keyword on heap area and it will be placed in the String constant pool. Finally it will be assigned to the reference variable, var3. This process is just by passing from String constant pool management. Therefore, (var1 == var3) is false.