Java Reference
In-Depth Information
Literals of type byte and short
There are no literals of types byte or short . However, if you use an int lit-
eral in a place where a byte (or short ) value is required, and if the value is in
the range of type byte (or short ), it will be accepted. For example, the first
statement below is legal, but the second is illegal because 128 is not in the range
of type byte :
byte b1= 127; // legal
byte b2= 128; // illegal, because 158 is too big
Operations of type byte and short
There are no operations of type byte or short . Instead, the following hap-
pens. Suppose b1 and b2 are of type byte . Then the operation b1+b2 is evaluat-
ed as follows:
1. Widen the values of b1 and b2 to type int .
2. Add the two values using int addition.
This means that any expression with an operation that is assigned to a byte or
short value has to be explicitly narrowed (see Sec. 6.3). Here is an example:
b1= ( byte ) (b1 + b2);
One might well ask why one would ever use types byte and short —why
not always use int ? Suppose one has a large collection, perhaps 1,000,000 val-
ues, each in a small range. Perhaps each is a day of the week, or the day of a
month, or the temperature during the day in Ithaca, NY. Stored as int s, they
require 4,000,000 bytes; stored as byte s, they require only 1,000,000. So, for
reasons of economy of space, types byte and short can be useful.
Type long
The values of type long are the integers in the range:
-9223372036854775808 .. +9223372036854775807 , or
-2 63 .. 2 63 -1 .
A value of type long occupies eight bytes of memory.
The following constants give the minimum and maximum values of type
long :
Search WWH ::

Custom Search