Keyword 'final' for java variables

Asked

Viewed 248 times

0

The ultimate java keyword for variables means it will only receive one value once, right?

If I have several variables in a function and I know that they should not receive any value later it is 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 statement as the end make any important difference in compiled code? Will gain/lose performance?

1 answer

4


There is no performance relationship. The main reason is just to link some more checks made by the compiler in search of errors.

When you put the modifier final In a variable, you’re telling the compiler to give you a build error if you somehow carelessly assign something to the variable. In the case of static or instance variables, the compiler also warns you of a build error if you simply forget to assign something. This is especially useful when you tamper with a code you developed months or years ago.

In short, it is something to prevent the programmer from shooting his own foot in some cases.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.