A Closer Look at Java Literals
A Closer Look at Java Literals
Literals were mentioned briefly in Chapter 2. Now that the builtin types have been formally
described, lets take a closer look at them.
Integer Literals
Integers are probably the most commonly used type in the
typical program. Any whole
number value is an integer literal. Examples are 1, 2, 3, and 42.
These are all decimal values,
meaning they are describing a base 10 number. Two other
bases that can be used in integer
literals are octal (base eight) and hexadecimal (base 16). Octal
values are denoted in Java by a
leading zero. Normal decimal numbers cannot have a leading
zero. Thus, the seemingly
valid value 09 will produce an error from the compiler, since 9
is outside of octals 0 to 7
range. A more common base for numbers used by
programmers is hexadecimal, which
matches cleanly with modulo 8 word sizes, such as 8, 16, 32,
and 64 bits. You signify a
hexadecimal constant with a leading zero-x, (0x or 0X). The
range of a hexadecimal digit is
0 to 15, so A through F (or a through f ) are substituted for 10
through 15.
Integer literals create an int value, which in Java is a 32-bit
integer value. Since Java is
strongly typed, you might be wondering how it is possible to
assign an integer literal to one
of Javas other integer types, such as byte or long, without
causing a type mismatch error.
Fortunately, such situations are easily handled. When a literal
value is assigned to a byte or
short variable, no error is generated if the literal value is within
the range of the target type.
An integer literal can always be assigned to a long variable.
However, to specify a long
literal, you will need to explicitly tell the compiler that the
literal value is of type long. You
do this by appending an upper- or lowercase L to the literal. For
example, 0x7ffffffffffffffL