Keyword 'final' for java variables

0

The final java keyword for variables means that it will only get a value once, right?

If I have multiple variables in a function and I know they should not receive any value later, is it good to declare them as "final"?

void foo() {
final int a = 0;

// executa alguma coisa
final int b = 0;
// ...
final String a = "a";
}

Will this final statement make any important difference in compiled code? Will you gain / lose performance?

    
asked by anonymous 05.10.2018 / 18:45

1 answer

3

There is no relationship to performance. The main reason is just to turn on some more checks by the compiler for errors.

When you set the final f modifier to a variable, you are telling the compiler to give you a compile error if you for some carelessness assign something to the variable twice. In case of static or instance variables, the compiler also warns you with a compile error if you just forget to assign something. This is especially useful when you tinker with a code you developed months or years ago.

In summary, it's something to keep the programmer from firing on his own foot in some cases.

    
05.10.2018 / 19:17