36

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?

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289

8 Answers8

64

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I also feel it helps in performing optimization. As value of this final variable wont change, JVM will cache the value of this variable to improve performance. – Ankur Shanbhag Aug 14 '13 at 07:32
  • 10
    @Ankur that hasn't been the case for a long time. The compiler can very easily work out if a variable is changed or not and optimise accordingly. Here's [another SO answer](http://stackoverflow.com/a/4279442/2071828) to that effect. – Boris the Spider Aug 14 '13 at 07:38
  • 2
    @Jon Skeet Is it correct to assume that these variable live beyond their local scope since they can be accessed by anonymous inner classes ? – Ahmed Jun 03 '14 at 04:07
  • 6
    @Ahmed: Well behind the scenes, the compiler generates an instance variable in the anonymous inner class and copies the value of the original variable when the instance is created. Whether that's more or less useful to you than thinking of the original variable living beyond its local scope is your call :) – Jon Skeet Jun 03 '14 at 05:38
  • Thanks for explanation. Just in case I would like to share this answer also: http://programmers.stackexchange.com/a/115711/156138 as it might be useful for others in future. – Adil Aliyev Sep 01 '16 at 02:05
9

final local variables may be accessed from anonymous inner subclasses, whereas non final local variables may not.

John Smith
  • 2,282
  • 1
  • 14
  • 22
8

Yes, the usability is :- local final variable are accessible by the method inner class. Since local variables live on the stack and exist only for lifetime of the method but Inner class object may live longer so inner class can't access any non final local variable. But once the variable is final then the inner class sure that the value won't change so it keep a private copy of the final local variable for use.

Krushna
  • 5,059
  • 5
  • 32
  • 49
  • This is the only answer i found to be something reasonably appropriate.. good one@Krushna – DJphy Oct 23 '15 at 09:45
6

Perfect answer Jon Skeet but there is another (little) benefit of final variables.

The compiler will ensure the final variable is set once and only once.

Let's say you have to initialize a variable and the computation of the value is complex (multiple if-then-else within if-then-else). You might write code that does not initialize the variable in some condition (or initialize it twice). Of course, this is a bug. Making the variable final will allow the compiler to check the final variable is set once and only once. So you will know quickly if you have a bug.

As I said, little benefit but still handy.

Algiz
  • 1,258
  • 9
  • 20
5

yes there is, a small expample where we could normally use it -

Snippet:

final Boolean data = Boolean.TRUE;
button.addListener(SWT.Selection, new Listener() {
    public void handleEvent(Event event) {
        if (data ) {
                     ....
                }
        }
});

Its a example of usage with anonymous inner classes. If you want to use your local variable inside inner calss, you have to make final.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
4

Use of final local variables in java

final fields, parameters, and local variables are read-only(means the object's identity, not its state).

Premraj
  • 72,055
  • 26
  • 237
  • 180
  • Sure, but any compiler worth its salt will recognize that the variable never changes inside the method, and treat it exactly the same as if it had been declared final. The only advantages are: someone reading or modifying the code will know the author's intent, and it prevents you from accidentally re-assigning the value. – Edward Falk Dec 01 '15 at 18:39
  • variables or reference types marked with final should and must initialize before compilation or else compilation fails. – Ajay Takur Oct 14 '18 at 16:13
3

You might use final keyword for readability and ensuring it is not modified or in anonymous classes like here:

    final String s = "hi";
    new Thread(new Runnable() {
        @Override
        public void run() {
            // can use s variable here
        }
    }).start();
Tala
  • 8,888
  • 5
  • 34
  • 38
3

It tells the other programmers that whoever wrote it knew that the value of data shouldn't change once assigned. It's a good habit in my opinion especially declaring the parameter variables as final.

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74