← All blog posts

Compile-time optimization with final keyword in Java

July 3, 2024 · Programming

Recently i noticed that the final keyword in Java can be used inside a method body. I was interested about the compiler’s behavior regarding this issue. So i i wrote the following program:

public class Test {
public static void main(String[] args) {
int i = 10;

System.out.println(i);
}
}

I compiled it and decompiled the produced class

javap -c Test
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public static void main(java.lang.String[]);
Code:
0: bipush 10
2: istore_1
3: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
6: iload_1
7: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
10: return
}

So far all are ok … just a program that prints out the number 10 after one assignment. I modified the program, and used the final keyword in the declaration of the variable i.

public class Test {
public static void main(String[] args) {
final int i = 10;

System.out.println(i);
}
}

The generated code is the following

javap -c Test
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: bipush 10
5: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
8: return
}

As we can see in the first case the variable i was stored in the method’s local variable area using the istore_1 and the iload_1 commands. In the second case these were ommited and the value 10 was inlined. I think it is typical for the final keyword to trigger this kind of optimization from the compiler. I am curious what happens in more complex cases. :)