Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of final local variables in java [duplicate]

I was wondering is there any usability of using final local variables. Variables are not overridden anyway when inheritance comes into picture. For example a simple code as below

public static void main(String args[]) {     final String data = "Hello World!";     System.out.println(data); } 

The example is quite simple one and may not be a relevant code but the question is more generic.I have seen a lot of codes(all incorporated in main function which have final local variables) Is there any usability of declaring local variables as final other than that they cannot be edited in the same function itself?

like image 991
Aniket Thakur Avatar asked Aug 14 '13 07:08

Aniket Thakur


People also ask

Why local variable is 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.

How do you resolve duplicate local variables in Java?

The solution is to either rename your second (duplicate) variable to something else (like in the example: b) or keep using the existing variable a (by not declaring it again, i.e. lose the second int in this example).

Should local variables be final?

Like methods, local variables and parameters need not to be declared final.

Why should variables be declared final?

A variable cannot be modified after it is declared as final. In other words, a final variable is constant. So, a final variable must be initialized and an error occurs if there is any attempt to change the value.


1 Answers

Firstly, the part about variables being "overridden" - final has two very different meanings. For classes and methods, it's about inheritance; for variables it's about being read-only.

There's one important "feature" of final local variables: they can be used in local (typically anonymous) inner classes. Non-final local variables can't be. That's the primary use of final for local variables, in my experience.

public void foo() {     final String x = "hello";     String y = "there";      Runnable runnable = new Runnable() {         @Override public void run() {             System.out.println(x); // This is valid             System.out.println(y); // This is not         }     };     runnable.run(); } 

Note that as a matter of style, some people like to use final even when they're not capturing the variable in a local inner class. I'd certainly be comfortable with final being the default, but a different modifier for "non-final", but I find that adding the modifier explicitly everywhere is too distracting.

like image 130
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet