Today while searching for a certain piece of code from google, I came across one Q/A blog, where its been said that we can declare a local variable inside a method of a class to be final. However, the author was reluctant enough to explain the need/ benefit of doing so.
like
public class A
{
private void show()
{
final String s="checking";
}
}
I would seek java gurus' help to educate me on this. Thanks in advance for your kind support and guidance.
Best regards!
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.
Local Variables We can put it in a method body. We declared num in the method body of main(). Variables declared inside a method are called local variables. Local variables can only be used within the method body.
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.
You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .
In addition to other answers, making a variable final
enables the use of that variable in inline implementation of classes and interfaces:
final String test = "test";
foo = new Foo() {
public void bar() {
System.out.println(test);
}
};
EDIT:
If you are a beginner it might also be worth pointing out that the variable is in fact a reference to an instance. When you make a variable final
you are in fact making the reference constant, that is, a final variable can never refer to some other instance after initialization. This makes no claims as to whether the actual referenced instance is constant.
For example, if you say final String[] foo = { "bar", baz" }
you can do foo[0] = "sheep"
even though foo
is final
. What you cannot do is reference foo
variable to something else, like in foo = new String[]...
or foo = someOtherArray
. This has to do with mutability and immutability and those concepts are somewhat akin to final
, so they might be worth some investigating.
The variable can be placed in read-only memory, making it faster to operate on.
Also it can simply be logical to do so, for instance for representing local constants or ensuring that a certain value is not accidentally changed. This makes it a useful way to turn bugs into compiler errors.
Also, it allows for the variable to be used within inner/anonymous classes, as pointed out by the other answers.
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