Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about local final variable in Java

Tags:

java

final

I have the following code:

public class BookLib {
    void f() {
        final int x = 5; // Line 1
        class MyCLass {
            void print() {
                System.out.println(x);
            }
        }
    }
}

I don't understand why should use final variable in this case (Line 1)?

like image 750
ipkiss Avatar asked May 10 '11 08:05

ipkiss


People also ask

Can local variables be final in Java?

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.

Why local variables are declared as final in Java?

final is the only allowed access modifier for local variables. final local variable is not required to be initialized during declaration. final local variable allows compiler to generate an optimized code. final local variable can be used by anonymous inner class or in anonymous methods.

When can final local variables be initialized?

Initializing a final Variable You can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a blank final variable.

Why should local variables be final or effectively final?

The local variables that a lambda expression may use are referred to as “effectively final”. An effectively final variable is one whose value doesn't change after it's first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error.


1 Answers

You've created an inner class here. Since the life-time of objects of this class can potentially be much greater than the runtime of the method invocation (i.e. the object can still exist long after the method has returned), it needs to "preserve" the state of local variables that it can access.

This preserving is done by creating an (invisible, synthetic) copy inside the inner class and automatically replacing all references to the local variable with references to that copy. This could lead to strange effects when the local variable were modified after the inner class object was created.

To avoid this, there is a requirement that all local variables that you access this way are final: this ensures that there is only ever one possible value for the local variable and no inconsistencies are observed.

This specific rule can be found in §8.1.3 Inner Classes and Enclosing Instances of the JLS:

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.

like image 71
Joachim Sauer Avatar answered Oct 15 '22 12:10

Joachim Sauer