0

While running PMD i got following message.

A local variable assigned only once can be declared final.

Does changing local variable to final OptimiZes the Code? If yes, What is the Effect?

That did not solve my problem. I am asking about is there any optimization to code?

Nikhil Kumar
  • 2,618
  • 3
  • 21
  • 24

1 Answers1

2

You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler/jdk that can lead to better optimization of the class file.

It's Effect : Well if you make a local variable final as per definition you can never change it. So in future if you want to assign a different value to the local variable you need to remove the final keyword. a bit of rework. Other than that i dnt see any harm why you shouldn't make a local variable final.

Ref book : "Hardcore Java" by Robert Simmons, Jr. The book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors.

Hope it helpful to you

Ravikiran butti
  • 1,668
  • 2
  • 11
  • 18
  • What kind of optimization it provides? – Nikhil Kumar Mar 16 '15 at 08:22
  • Imagine a situation when your given 2 precious item, one has expiry date on when it has to be polished and other has no expiry date. what will do when you save these item. One which requires polishing you will keep it infront of your eyes and timely check its expiration date is near. For other you will just throw it some where since it doesnt require much of your attention. That exactly is the behaviour of JVM with your final and non final variables :) – Ravikiran butti Apr 01 '15 at 10:11