The following question provides an example of determining
the maximum value of three of the integral primitive
types--byte, short, and character.
class A {
public static void main(String args[]) {
System.out.print(Long.toHexString(Byte.MAX_VALUE)+",");
System.out.print(Long.toHexString(Character.MAX_VALUE)+",");
System.out.print(Long.toHexString(Short.MAX_VALUE));
}
}
What is the result of attempting to compile and run the program?
a. Prints: f,ff,7f
b. Prints: f,ff,ff
c. Prints: 7f,ffff,7fff
d. Prints: ff,ffff,ffff
e. Prints: 7fff,ffffff,7fffff
f. Prints: ffff,ffffff,ffffff
g. Compiler Error
h. Runtime Error
i. None of the Above
To answer this question you need to know three things about
each of the three data types--byte, short, and char.
Type byte represents an 8 bit signed value using the
two's compilment representation of binary numeric
values. The left most
bit is the sign bit. The sign bit is set to one
for negative values and is set to zero for positive
values. The largest positive byte value has
the sign bit set to zero and the other seven
bits set to one.
Byte.MAX_VALUE = 01111111
The above binary value is extremely easy to convert
to hexadecimal. Each hex digit represents four binary
bits so the left four bits represent one hex digit and
the right four bits represent the second hex digit.
Binary 0111 1111
Hex 7 f
Please note that 0111 = 4 + 2 + 1 = 7. Similarly,
1111 = 8+4+2+1 = 15 (decimal) = f (hex).
Short is a signed 16 bit value so the binary representation
of Short.MAX_VALUE is as follows.
Binary 0111 1111 1111 1111
Hex 7 f f f
Type char and type short both represent 16 bit values.
The two types differ in that char is unsigned
while short is signed. As a result, type char has no
sign bit and all char values are positive.
Character.MAX_VALUE is represented as follows.
Binary 1111 1111 1111 1111
Hex f f f f
The binary and hexadecimal representations of
Integer.MAX_VALUE are similar to those of
Short.MAX_VALUE.
The two types differ only in size. Type short
is 16 bits while type int is 32 bits.
Binary 0111 1111 1111 1111 1111 1111 1111 1111
Hex 7 f f f f f f f