App Kart
App Kart

Reputation: 926

Why local variables are final?

Why local variable make as final whether method argument or inside method.

private void add(final int a , final int b) {
    final int c = 0;
}

Please anyone clarify.i am searching a lot but i did not find exact answer.

Upvotes: 0

Views: 238

Answers (3)

Israel Unterman
Israel Unterman

Reputation: 13510

Functional style uses final variables. This is one reason. Another one is closures.

Final variables are the only ones that can be used in closures. So if you want to do something like this:

void myMethod(int val) {
    MyClass cls = new MyClass() {
        @override
        void doAction() {
            callMethod(val);  // use the val argument in the anonymous class - closure!
        }
    };
    useClass(cls);
}

This won't compile, as the compiler requires val to be final. So changing the method signature to

void myMethod(final int val)

will solve the problem. Local final variable will do just as well:

void myMethod(int val) {
    final int val0;
    // now use val0 in the anonymous class

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35011

final in these instances simply means that the values cannot be changed. Trying to set another value to any of your final variables will result in a compile-time error

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272257

One reason is it prevents you inadvertently changing them. It's good practise since it'll catch some hard-to-spot coding mistakes.

The second reason is that if you're using inner classes, variables referenced from an outer scope need to be declared as final. See this SO answer for more detail.

The problem with final is that it means different things in different contexts. See this discussion for more info.

Upvotes: 6

Related Questions