Re: Math.min and Math.max for byte / short
Philipp wrote:
On Jul 21, 11:10 pm, Eric Sosman <Eric.Sos...@sun.com> wrote:
Roedy Green wrote:
On Mon, 21 Jul 2008 08:06:45 -0700 (PDT), con...@lewscanon.com wrote,
quoted or indirectly quoted someone who said :
byte c = (byte) Math.min ( a, b );
The inventors of java.lang.Math *could* have provided
byte-valued overloads of min, max, etc:
I guess they just didn't feel it was important enough.
Hmm. Oh well. They provided it for double float int and long. I guess
they could have made the effort to type the three missing ones eh?
[Uninformed speculation] For most operators, like + and /
and so on, applying the operator to a pair of double operands
yields a double result, floats yield a float, longs yield a
long, and ints yield an int. But applying the operator to a
pair of shorts or a pair of chars or a pair of bytes yields an
int value, not a short or char or byte[*]. You cannot just write
`bsum = b1 + b2' but must write `bsum = (byte)(b1 + b2)' -- and
maybe what's more to the point, you're "accustomed" to writing
the cast[**]. So the j.l.M authors may well have thought it no
hardship to require you to write casts on max() et al. as well.
[* More uninformed speculation] The promotion of "narrow"
integer operands to ints makes for a better match between Java
bytecode and the machines that implement it. Lots of machines
have no instructions to operate on narrow integers; rather, they
have "widening" instructions to load narrow values into wide
registers and "narrowing" instructions to store wide values into
narrow destinations. The arithmetic usually takes place on the
widened in-register operands, at the widened precision. The
bytecode itself reflects this: It makes no distinction between
bytes, shorts, and ints once they've been pushed onto the stack,
and it has no instructions for arithmetic on bytes or shorts.
[** Still more uninformed speculation] Java *could* have
been defined to be silent about precision-losing conversions, but
somebody seems to have considered it helpful to bring them to the
programmer's attention by requiring a cast. This may improve the
safety of calculations on bytes and shorts (and chars, if you go
in for that sort of thing), but the silent loss of precision in
calculations on int and long seem far more troublesome. But I'm
adrift on the deep blue C, where silent chopping is common, and
the experience may have warped my perspective. I'm not aware of
any research on whether Java's insistence on a cast does or does
not decrease error rates -- but I haven't been looking for it.
--
Eric.Sosman@sun.com