Java: why should a local variable be declared final

Possible duplicate:
Is there a performance reason for declaring final method parameters in Java?
Why mark local variables and method parameters as "final" in Java?

I use PMD to view code violations.

Inside the webService method, I have the code below

public ServiceRequest getData() { Status status = new Status(); // code } 

What PMD offers me is that this local variable value can be declared final.

My question is, what can the final result lead to any performance improvements or, if that doesn't help, what can the code get?

+6
source share
3 answers

Adapted from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23

  • clearly conveys your intentions
  • allows the compiler and virtual machine to perform minor optimizations
  • clearly denotes elements that are easier to behave - the final says: "If you are looking for complexity, you will not find it here."

This is also discussed in this question: Can overuse of end pain be more than doing good?

+4
source

final indicates that the local variable will not be changed. I feel that the methods should be so short that you should be able to understand them easily, and so ending the variable may be a little redundant.

I prefer to make final fields because making the whole class so short is a serious limitation. Fields can also have thread safety issues that do not have local variables.

+4
source

I don’t know about the performance benefits of making status final, but PMD offers you this because maybe you never record the status after its first initialization.

So, what you get by making it final is that your code is less error prone - if you declare it final, you cannot rewrite it by mistake ...

+1
source

Source: https://habr.com/ru/post/907952/


All Articles