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 :
- 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
- 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
// static int x will also not work.
error: illegal start of expression
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Are static local variables allowed in Java?
- final variables in Java
- Assigning values to static final variables in Java
- Static and non static blank final variables in Java
- Unreachable statement using final and non-final variable in Java
- Local Inner Class in Java
- Initialization of local variable in a conditional block in Java
- Local Variable Type Inference or LVTI in Java 10
- Blank Final in Java
- Using final with Inheritance in Java
- final keyword in java
- Final arrays in Java
- final vs Immutability in Java
- final, finally and finalize in Java
- Final static variable in Java