Compile-time optimization with final keyword in Java

Vassilios Karakoidas
2 min readJul 3, 2024

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);
}
}

--

--

Vassilios Karakoidas

Software Engineer, Software Architect, Researcher. Opinions are my own.