What are local variables?
A local variable is a variable that is declared within a method. Local variables are only accessible within the method in which they are declared. They are not accessible from anywhere else in the class. Local variables are not given default values and must be initialized before they can be used.
What are inner classes?
Inner classes are classes that are defined within another class. They are sometimes called nested classes. Inner classes are a powerful feature of the Java programming language. They can be used to encapsulate data, to organize code, and to improve the functionality of existing classes.
Why do local variables referenced from an inner class have to be final or effectively final?
The reason has to do with the way inner classes work. When you create an instance of an inner class, the instance contains a reference to an enclosing instance (if any). For the inner class to be able to access the enclosing instance’s variables, they have to be marked as final (or effectively final).
If you try to compile a program that contains an inner class that references a non-final local variable, you’ll get an error message like this:
local variables referenced from an inner class must be final or effectively final
What are some ways to make a local variable effectively final?
There are a few ways to make a local variable effectively final:
- Assign the variable only once
- Use the variable only from within a lambda expression or an anonymous class
- Use primitive types instead of objects (this doesn’t apply to arrays)
If you need to modify a local variable inside an inner class or lambda expression, you can declare the variable as a member of the outer class.
Are there any exceptions to the rule that local variables referenced from an inner class have to be final or effectively final?
No, there are no exceptions to the rule. Local variables referenced from an inner class must be declared final, or they must be effectively final.