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.
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.
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.
Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With