Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is final the only modifier for local variables in Java?

Tags:

java

jvm

class Test {

    public static void main(String[] args) {
        private int x = 10;
        public int y = 20;
        protected int z = 30;
        static int w = 40;  
        final int i = 50;
    }
}

The only applicable modifier is final here; for other modifiers, the program gives compiler errors. Why is that? Please explain in detail.

like image 269
anirban karak Avatar asked Oct 03 '13 18:10

anirban karak


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.

Why should local variables be final or effectively final?

The local variables that a lambda expression may use are referred to as “effectively final”. An effectively final variable is one whose value doesn't change after it's first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error.

Which modifiers are used with local variables in Java?

Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final.

Why is the final modifier important to security in Java?

When a final modifier is used with a class then the class cannot be extended further. This is one way to protect your class from being subclassed and often sensitive classes are made final due to security reasons. This is also one of the reasons why String and wrapper classes are final in Java.


1 Answers

In short - none of the other modifiers make sense in that context. Saying a variable is public, private, protected, or static simply doesn't make sense in the context of a local variable that will go out of scope (and be garbage collected) once the method exits. Those modifiers are intended for class fields (and methods), to define their visibility (or in the case of static, their scope).

final is the only one that makes sense in the context of a local variable because all it means is that the variable cannot be modified after its initial declaration, it has nothing to do with access control.

like image 116
StormeHawke Avatar answered Sep 25 '22 08:09

StormeHawke