Why is the java compiler not giving any compile time error for method level local final variables when we not initialize them?
( but it is giving en error for instance level final variables when they are not initialized ).
public class FinalKeyword
{
final int j; // error: the blank final field j may not have been initialized.
public static void main(String[] args)
{
final int k; // not giving any Compile time error!
}
}
Thing is: as soon as you change your main() method to
final int k;//Not Giving any Compile time error
System.out.println(k); //different story now!
You get an error about k not being initialized, too!
The point is:
new FinalKeyword() without problems. Thus it can't allow you to keep j not initialized.main() method ... even when another method invokes this main() method - that is fine. The method does nothing! In other words - it is not a problem to define a variable that doesn't get used within a method! Because there is no way how you could get to that variable!The compiler has to prevent you from getting into situations where you "stumble" over an uninitialized variable. When you invoke a method that has such variables ... but never uses them - that is simply a "don't care".
And surprise: when we go with
public class FinalTest {
public static void main(String args[]) {
final int k;
}
}
and compile that; and then we use javap to get to de-compiled byte code:
public static void main(java.lang.String[]);
Code:
0: return
This is one of the rare occasions where javac does a bit of optimization - by simply throwing away unused variables. Bonus fun fact: even when changing my example to k=5; - you will find that the class file still only contains return!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With