Java Reference
In-Depth Information
3.2.1
Java has a number of built-in scalar (in this context, nonobject) types. We
discuss these below.
Scalar Types
3.2.1.1
Java defines four integer types— byte , short , int , and long . Unlike some
languages, Java defines the precision, that is, the bit size, of these types.
Integer Types
byte : 8 bits
short : 16 bits
int : 32 bits
long : 64 bits
For Java, the goal is “compile once, run anywhere.” Defining that int
means 32 bits—everywhere—helps to achieve this goal. By contrast, when C
language was first defined, its goal was different: to be available quickly on a
variety of architectures, not to produce object code that would be portable be-
tween architectures. Thus, for C, the choice was up to the compiler developer
to choose a size that was most “natural” (i.e., convenient) for that particular
architecture. 2 This would make it easiest on the compiler writer. It
succeeded—C was an easy language to implement, and it spread widely.
Back to Java. Note that all these values are signed. Java has no
“unsigned” type.
Note also that byte is listed here. It can be treated as a numeric value, and
calculations performed on it. Note especially that it is a signed number (i.e.,
values range from -128 to 127 and not from 0 to 255). Be careful when pro-
moting a byte to an int (or other numeric value). Java will sign-extend on the
promotion. If the value in the byte variable was a character (e.g., an ASCII
value) then you really wanted it treated like an unsigned value. To assign such
a value to an int you'll need to mask off the upper bits, as in Example 3.1.
You may never encounter such a situation, but if you are ever working
with bytes (e.g., byte arrays) and start to mess with the individual bytes, don't
say we didn't warn you.
2. In fact, C's only rule is that a short int will not be longer than an int and a long will
not be shorter than an int . It is both ANSI and K&R compatible for all integer types in a C
compiler to be the same size!
Search WWH ::




Custom Search