Local variable - redundant java

Can someone explain to me why this gives me a "local variable - redundant error"?

public double depreciationAmount() { double depreciationAmount = (cost * percentDepreciated); return depreciationAmount; } 
+6
source share
3 answers

Can someone explain to me why this gives me a "local variable - redundant error"?

Because you can trivially write this without using a local variable.

 public double depreciationAmount() { return cost * percentDepreciated; } 

Therefore, the local variable is not needed / redundant.


However, I assume this is NOT a compiler error. This may be a compiler warning, or most likely a style check or an error warning. This is something you could ignore without risking the correctness of your code ... as it is written.

In addition, I would predict that after the code was compiled by JIT (using the modern compiler Hotspot JIT ...), there will be no difference in performance between the two versions.

+13
source

Although this is not the case here if a redundant local variable is required (I had it once when it was, without any details), here is how to suppress this particular warning.

 @SuppressWarnings("UnnecessaryLocalVariable") public double depreciationAmount() { double depreciationAmount = (cost * percentDepreciated); return depreciationAmount; } 
+4
source

You only use the percentDepreciated value to return it when you could just do return (cost * percentDepreciated)

+1
source

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


All Articles