collint25 collint25 - 20 days ago 9
Java Question

Local variable is redundant java

Can someone explain to me why it's giving me "local variable is redundant error"?

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

Answer

Can someone explain to me why it's giving me "local variable is redundant error"?

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

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

Hence the local variable is unnecessary / redundant.


However, I surmise that this is NOT a compiler error. It might be a compiler warning, or more likely it is a style checker or bug checker warning. It is something you could ignore without any risk to the correctness of your code ... as written.

Also, I would predict that once that the code has been JIT compiled (by a modern Hotspot JIT compiler ...) there would be no performance difference between the two versions.