Open In App

Final local variables in Java

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite : final keyword, Variables, Scope of Variables

A local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists. If we are declaring a local variable then we should initialize it within the block before using it. In case of local variable, JVM won’t provide any default values.

A final local variable serves as a warning when you “accidentally” try to modify a value and also provides information to the compiler that can lead to better optimization of the class file.

Usability of using final local variables:

  • Most importantly, We can use local variable as final in an anonymous inner class, we have to declare the local variable of anonymous inner class as final. This is to do with the individual accessor methods that get generated to implement the anonymous inner class. Non-final local variables can’t be used for inner classes
  • It may allow Java compiler or Just In Time compiler to optimize code, knowing that the variable value will not change. This can improve the processing time of the program.

Important points about local final variable :

  1. Initialization of the variable is not Mandatory: Even though local variable is final we have to perform initialization only if you want to use it i.e. if we are not using then it is not required to perform initialization even though it is final.




    // Java program to illustrate the behavior of
    // final local variable
    class Test {
        public static void main(String[] args)
        {
            final int x;
            System.out.println("GEEKS");
        }
    }

    
    

    Output:

    GEEKS
    
  2. Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final. By mistake if we trying to apply any other modifier then we will get compile time error.




    // Java program to illustrate that final is
    // the only applicable modifier for local variable
    class Test {
        public static void main(String[] args)
        {
            public int x; // static int x will also not work.
            System.out.println("GEEKS");
        }
    }

    
    

    Output:

    error: illegal start of expression
    


Last Updated : 25 Sep, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads