Constant pool

Suman Ganta
suman_ganta
Published in
2 min readMay 5, 2007

Do you know the below facts about constant pool?

1. Constants will not be initialized during compile time if the assigned constant cannot be computed during compile time.
2. addition of two constant string literals will be performed during compile time by compiler
3. Addition of string literal with a static string variable (though it is initialized to a string literal) will not be performed by compiler.

Above facts can be tested with below code snippet that uses Apache byte code engineering library — A library that parses the class file and allows us to examine all of its parts. Other part of this library allows dynamically generating class files!!

import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;


public class CPExamination {
public static final String str1 =”str1"; //str1 is initialized during compile time
public static final String str2 =”str2"; //str2 is initialized during compile time
public static final String str3 =str1+str2; //This is compile time addition and str3 is initialized at compile time
public static String str4 = “ABC”; //str4 is initialized during runtime though “ABC” is a constant pool entry
public static final String str5 =”str5" + str4; //This is runtime addition

public void examineClass(JavaClass clazz) throws Exception{
Field[] fields = clazz.getFields();
// Test field initialization. values of str4 and str5 will be printed as nulls here

for(int i=0; i<fields.length; ++i)
System.out.println(fields[i].getConstantValue());

Constant[] constants = clazz.getConstantPool().getConstantPool();
ConstantPool cpool = clazz.getConstantPool();

//Test string literal computation (addition) here by inspecting constant pool

//Here “str1str2” (result of str3=str1+str2) will be stored in constant pool

for (int i=0; i<constants.length; ++i){
if(constants[i] != null && constants[i] instanceof ConstantUtf8)
System.err.println(cpool.constantToString(constants[i]));
}
}

public static synchronized void main(String[] args) throws Exception{
ClassParser parser = new ClassParser(“bin/” + CPExamination.class.getName() + “.class”);
JavaClass clazz = parser.parse();
new CPExamination().examineClass(clazz);
}
}

--

--