Consider this code snippet
public class ConstantFolding {
static final int number1 = 5;
static final int number2 = 6;
static int number3 = 5;
static int number4 = 6;
public static void main(String[ ] args) {
int product1 = number1 * number2; //line A
int product2 = number3 * number4; //line B
}
}
What is the difference between the line marked as line A and the line marked as line B?
The difference is that the multiplication required for
product1is performed at compile-time asnumber1andnumber2are constants.The calculation for
product2is compiled at execution time, as the values ofnumber3andnumber4can change. Indeed, you could change the values and then callmainagain.See sections 15.28 and 4.12.4 of the JLS for more information about constant expressions and constant variables.