While designing and development, one should think in terms of compile-time and run-time.It helps in understanding language basics in a better way.Let's understand this with a question below :
What is the difference between line 1 & line 2 in the following code snippet?
public class CompileAndRuntimeTest{
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 1
int product2 = number3 * number4; //line 2
}
}
Line 1, evaluates the product at compile-time, and Line 2 evaluates the product at runtime. If you use a Java Decompiler (e.g. jd-gui), and decompile the compiled CompileAndRuntimeTest.class file, you will see why , as shown below:
public class CompileAndRuntimeTest
{
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 = 30;//line 1 ---Here is the diff. Decompiled code
int product2 = number3 * number4; //line 2
}
}
Constant folding is an optimization technique used by the Java compiler. Since final variables cannot change, they can be optimized. Java Decompiler and javap command are handy tool for inspecting the compiled (i.e. byte code ) code.
Question for readers :) :
Can you think of scenarios other than code optimization, where inspecting a compiled code is useful?