Java Reference
In-Depth Information
b. The value must be too large (a positive value of large magnitude or positive
infinity), and the result of the first step is the largest representable value of
type
int
or
long
.
2.
In the second step:
• If
T
is
int
or
long
, the result of the conversion is the result of the first step.
• If
T
is
byte
,
char
, or
short
, the result of the conversion is the result of a narrowing
Example 5.1.3-1. Narrowing Primitive Conversion
class Test {
public static void main(String[] args) {
float fmin = Float.NEGATIVE_INFINITY;
float fmax = Float.POSITIVE_INFINITY;
System.out.println("long: " + (long)fmin +
".." + (long)fmax);
System.out.println("int: " + (int)fmin +
".." + (int)fmax);
System.out.println("short: " + (short)fmin +
".." + (short)fmax);
System.out.println("char: " + (int)(char)fmin +
".." + (int)(char)fmax);
System.out.println("byte: " + (byte)fmin +
".." + (byte)fmax);
}
}
This program produces the output:
long: -9223372036854775808..9223372036854775807
int: -2147483648..2147483647
short: 0..-1
char: 0..65535
byte: 0..-1
The results for
char
,
int
, and
long
are unsurprising, producing the minimum and max-
imum representable values of the type.
The results for
byte
and
short
lose information about the sign and magnitude of the nu-
meric values and also lose precision. The results can be understood by examining the
low order bits of the minimum and maximum
int
. The minimum
int
is, in hexadecimal,
0x80000000
, and the maximum int is
0x7fffffff
. This explains the
short
results, which are