You can obviously optimize it using a local variable... and such an optimization is always good as it makes you code clearer and less repetitive.
However, assuming you compareTo
is a simple side-effect free method, the JVM will probably inline it and can do this optimization for you. I guess, this is what you actually wanted to know.
There's no easy way to find it out, especially using println
must fail, as the JVM is allowed to make you program faster, but not behaving differently. You can't see it in the bytecode, as this contains no optimizations at all, they happen when the programs runs for a while.
The JVM is also not allowed to improve you coding style, so I'd suggest to use local variables, especially for more complicated expressions.
Your last condition is obviously always true, when reached. If you want the code to look systematically and symmetrically, use this
public void genericComparisons(Comparable e, Comparable target) {
int cmp = e.compareTo(target);
if (cmp < 0) {
// less
} else if (cmp > 0) {
// greater
} else {
// same
}
}