Search code examples
javadeclarationkeywordfinal

Un-initialized final local variable vs un-initialized final instance variable


As per my knowledge, final variables must/can be initialized only once otherwise compiler is supposed to throw an error.

If the final instance variable x is not initialized an error is thrown but I faced no error when the local variable y is kept uninitialized in the following code:

import java.util.*;
public class test
{
 final int x = 5;// if final variable x uninitialized, compilation error occurs
 public static void main(String[] args)
 {
     final int y;   // y is not initialized, **no error is thrown** 
     System.out.println("test program");
 }
}

Solution

  • import java.util.*;
    public class test
    {
     final int x = 5;
     public static void main(String[] args)
     {
         final int y;
         System.out.println("test program");
         y=6;
         y=7;   
     }
    }
    

    y=7 will give error:The final local variable y may already have been assigned. Since it is a final variable, and it has been assigned to 6.

    IMHO, a final local variable means once assigned, it cannot be re-assigned. But by final int y you are only declaring a final variable without assignment(initialization), which is legal in Java.(But in order to use it you still have to initialize it, or an error occurs.)

    Update:

    As commented below, you have noticed the difference between a class field final variable and a local final variable.

    From Java Language Specification:

    1. a final field must be definely assigned in the static initializer or the constructor:

      8.3.1.2 final Fields A field can be declared final (§4.12.4). Both class and instance variables (static and non-static fields) may be declared final. A blank final class variable must be definitely assigned by a static initializer of the class in which it is declared, or a compile-time error occurs (§8.7, §16.8). A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared, or a compile-time error occurs (§8.8, §16.9).

    (Note that a non-final field can be left un-initialized)

    2.A local variable(whether final or not) must be explicitly given a value before it is used:(chapter 4.12.5,P88)

    • A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).