Java Reference
In-Depth Information
< Day Day Up >
Puzzle 24: A Big Delight in Every Byte
This program loops through the
byte
values, looking for a certain value. What does the program
print?
public class BigDelight {
public static void main(String[] args) {
for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
if (b == 0x90)
System.out.print("Joy!");
}
}
}
Solution 24: A Big Delight in Every Byte
The loop iterates over all the
byte
values except
Byte.MAX_VALUE
, looking for
Ox90
. This value fits
in a byte and is not equal to
Byte.MAX_VALUE
, so you might think that the loop would hit it once and
print
Joy!
on that iteration. Looks can be deceiving. If you ran the program, you found that it prints
nothing. What happened?
Simply put,
Ox90
is an
int
constant that is outside the range of
byte
values. This is counterintuitive
because
Ox90
is a two-digit hexadecimal literal. Each hex digit takes up 4 bits, so the entire value
takes up 8 bits, or 1 byte. The problem is that
byte
is a signed type. The constant
0x90
is a positive
int
value of 8 bits with the highest bit set. Legal
byte
values range from -128 to +127, but the
int
constant
0x90
is equal to +144.
The comparison of a
byte
to an
int
is a
mixed-type comparison
. If you think of
byte
values as
apples and
int
values as oranges, the program is comparing apples to oranges. Consider the
expression
((byte)0x90 == 0x90)
. Appearances notwithstanding, it evaluates to
false
. To
compare the
byte
value
(byte)0x90
to the
int
value
0x90
, Java promotes the
byte
to an
int
with a
widening primitive conversion [JLS 5.1.2] and compares the two
int
values. Because
byte
is a
signed type, the conversion performs
sign extension
, promoting negative
byte
values to numerically
equal
int
values. In this case, the conversion promotes
(byte)0x90
to the
int
value
-112
, which is
unequal to the
int
value
0x90
, or
+144
.
Search WWH ::
Custom Search