Use of final local variables in java [duplicate]

2019-01-23 01:34发布

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?

8条回答
forever°为你锁心
2楼-- · 2019-01-23 02:13

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.

查看更多
Evening l夕情丶
3楼-- · 2019-01-23 02:14

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.

查看更多
登录 后发表回答