Local variable is redundant java

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.


I won't attempt to address the issue as to whether the warning is appropriate1. If you feel it is inappropriate, then https://stackoverflow.com/a/40709915/139985 explains how to suppress it.

1 - Except to say that it is too much to expect current generation style checkers to know when so-called explaining variables are needed. First you'd need to get people to agree on whether or not the variables are needed.


Although not the case here, if having redundant local variable is desired (I've had one time where this was the case - without getting into specifics), here's how to suppress this specific warning.

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

Tags:

Java