Monday, June 21, 2010

Resolution of Constant's in Java

Variables declared with keywords static and final are constants in java. Constants are resolved at compile time.

Consider the below code,

public class StudentType {

public static final boolean isNewStudent = true;

}

public class Student {

public static void main(String args[]) {

if(StudentType.isNewStudent) {
System.out.println("Welcome to our Institution!!");
}
}

}

When the Class Student is compiled, bytecode for main method includes the body of if statement but not for the check of StudentType.isNewStudent value.The constant pool of Student class has no symbolic reference to class StudentType, its value is placed in if condition and will not change as it is declared final.

However if you change the source code of class StudentType and set the variable to false and recompile the class StudentType and execute class Student then if statement gets executed as before, as the value of StudentType.isNewStudent was assigned at compile time. In order for the change to reflect Student class also has to be recompiled and then executed.

Whereas if the StudentType.isNewStudent were resolved at runtime time then it's value would be checked at each execution of Student class and thus change would have been reflected hence if statement wouldn't be included in bytecodes.

No comments:

Post a Comment