简体   繁体   中英

local variable made final in method of a class — but why?

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!

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.

Apart from enforcing the variable to remain unchanged after its initialization, declaring a variable as final makes it accessible to the method local inner classes.
More detailed information can be obtained by looking at the Disassembled code for the following small piece of code:

class MyFinal 
{
    public static void main(String[] args) 
    {
        String str = "java";
        final String str1 = "Hello";
    }
}

The disassembled code for the above program is as follows:

J:\>javap -c MyFinal
Compiled from "MyFinal.java"
class MyFinal extends java.lang.Object{
MyFinal();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   ldc     #2; //String java
   2:   astore_1
   3:   return

}

In main method of above disassembled code we see that , the java compiler has kept the code for String object creation of non-final variable str but it has silently omitted the String object creation code for final String str1 = "Hello"; . It is so because, str1 is not used in the method anywhere. Hence it helps compiler to optimize the code , which lead to avoidance of unnecessary object creation if there is no use of it.

It makes sensee to be able to tell easily that the variable won't change. If this is a primitive, you can consider the value being immutable, and if it is not, you now know that the value will always be the same instance (which state can be changed).

This is useful for readability of the program so that we are sure that the variable is never reassigned. It is also useful for anonymous functions, explained here: Why do we use final keyword with anonymous inner classes?

Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code.

Taken from this answer to a similar question.

when a var is final, you can't change it. that means - one mistake you can't do - or, if to be more precise, one logical mistake that will create a compiling error, and saving long debugging.


not to be mixed up with a final class that you can't inherit from.


more data could be found in wikipedia

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM