Java Reference
In-Depth Information
Although the meaning and usage of literals is intuitive most of the time, Java has some
special types of literals that represent different kinds of numbers, characters, strings, and
Boolean values.
Number Literals
Java has several integer literals. The number 4, for example, is an integer literal of the
int variable type. It also can be assigned to byte and short variables because the num-
ber is small enough to fit into those integer types. An integer literal larger than an int
can hold is automatically considered to be of the type long . You also can indicate that a
literal should be a long integer by adding the letter L (upper- or lowercase) to the num-
ber. For example, the following statement treats the value 4 as a long integer:
2
pennyTotal = pennyTotal + 4L;
To represent a negative number as a literal, prepend a minus sign (“-”) to the literal—for
example, -45.
NOTE
Java also supports numeric literals that use octal and hexadeci-
mal numbering.
Octal numbers are a base-8 numbering system, which means that
they can represent only the values 0 through 7 as a single digit.
The eighth number in octal is 10 (or 010 as a Java literal).
Hexadecimal is a base-16 numbering system that can represent
each of 16 numbers as a single digit. The letters A through F rep-
resent the last six digits, so the first 16 numbers are 0, 1, 2, 3,
4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
The octal and hexadecimal systems are better suited for certain
tasks in programming than the normal decimal system. If you have
ever used HTML to set a web page's background color, you might
have used hexadecimal numbers.
If you need to use a literal integer with octal numbering, prepend a
0 to the number. For example, the octal number 777 would be the
literal 0777. Hexadecimal integers are used as literals by
prepending the number with 0x, as in 0x12 or 0xFF.
Floating-point literals use a period character (“.”) for the decimal point, as you would
expect. The following statement uses a literal to set up a double variable:
double myGPA = 2.25;
Search WWH ::




Custom Search