Apart from enforcing the variable to remain unchanged after its initialization, declaring a variable as final
makes it accessible to the method local inner classes.
More detailed information can be obtained by looking at the Disassembled code for the following small piece of code:
class MyFinal
{
public static void main(String[] args)
{
String str = "java";
final String str1 = "Hello";
}
}
The disassembled code for the above program is as follows:
J:\>javap -c MyFinal
Compiled from "MyFinal.java"
class MyFinal extends java.lang.Object{
MyFinal();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2; //String java
2: astore_1
3: return
}
In main method of above disassembled code we see that , the java compiler has kept the code for String object creation of non-final
variable str
but it has silently omitted the String object creation code for final String str1 = "Hello";
. It is so because, str1
is not used in the method anywhere. Hence it helps compiler to optimize the code , which lead to avoidance of unnecessary object creation if there is no use of it.