It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.
No, what is "strange" is that you can use the +
and -
operators on Long objects. Before Java 5, this would have been a syntax error. Then autoboxing/unboxing was introduced. What you're seeing in this code is autounboxing: the operators require primtives, so the compiler automatically inserts a call to longValue()
on the objects. The arithmetic is then performed on primitive long
values, and the result is also a long
that can be stored without further conversion on the variable.
As for why the code does this, the real question is why someone would use the Long
type instead of long
. Possible reasons:
- The values come from some library/API that delivers
Long
values.
- The values are stored in collections (
List
, Map
), which cannot hold primitives.
- Sloppiness or cargo cult programming.
- The ability to have
null
values is required, e.g. to signal unavailable or uninitialized data.
Note that the ability of Long
to hold null
values means that the calculation (or more specifically, the longValue()
calls inserted by the compiler) can fail with a NullPointerException
- a possibility the code should deal with somehow.
Long
has been used at all. It is far less efficient. – Handoffa
,b
andc
might benull
, as you'll get a not-very-obviousNullPointerException
when the autounboxing calls.longValue()
on them in the expression. – Khorma