Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Compile Time error for instance level Final variables and not giving for method level local variables [duplicate]

Tags:

java

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!
    }
}
like image 632
suraj.kaudgave Avatar asked Jul 10 '26 12:07

suraj.kaudgave


1 Answers

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:

  • the compiler has to make sure that other source code that isn't visible right now ... is able to do a new FinalKeyword() without problems. Thus it can't allow you to keep j not initialized.
  • but that 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!

like image 87
GhostCat Avatar answered Jul 28 '26 17:07

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!