Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare a java field 'final' when if it's not modified in code?

My question is mainly about performance. The compiler knows better that, for example, some variable is NOT modified after object instantiation. So, why bother with final?

I presume many structural/logical reasons might come here, but speaking from the performance point of view? Does it matter?

Thanks,

like image 279
Ivan Balashov Avatar asked Aug 15 '11 15:08

Ivan Balashov


People also ask

When should a field be final Java?

A final field is one that cannot be changed once it is initialized. This means slightly different things for primitive and class types.

Is final necessary Java?

In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can't be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.

Is it good practice to use final in Java?

the reader of the code need not to reason at all about the value of a final variable (except for rare bad-code cases). So, yes, it's a good practice.

Why do we declare a variable as final in Java?

Java For TestersA variable cannot be modified after it is declared as final. In other words, a final variable is constant. So, a final variable must be initialized and an error occurs if there is any attempt to change the value.


1 Answers

In a modern JVM, final shouldn't affect performance. This is especially true for private fields, but even for non-private fields the JIT can optimize non-final fields as thought they are final, and then deoptimize if it loads some code that actually does modify the field.

That said, the main reason to use final is not performance, but to make your code more maintainable. By making fields final you are reducing the number of "moving parts" readers of your code have to think about, making it much easier to reason about the code.

like image 171
Laurence Gonsalves Avatar answered Sep 26 '22 02:09

Laurence Gonsalves