Java Reference
In-Depth Information
Java literals can be of any of the primitive data types. The way each literal is represented
depends upon its type. As explained earlier, character constants are enclosed in single
quotes. For example, 'a' and ' %' are both character constants.
Integer literals are specified as numbers without fractional components. For example, 10
and -100 are integer literals. Floating-point literals require the use of the decimal point fol-
lowed by the number's fractional component. For example, 11.123 is a floating-point liter-
al. Java also allows you to use scientific notation for floating-point numbers.
By default, integer literals are of type int . If you want to specify a long literal, append
an l or an L. For example, 12 is an int , but 12L is a long .
By default, floating-point literals are of type double . To specify a float literal, append an
F or f to the constant. For example, 10.19F is of type float .
Although integer literals create an int value by default, they can still be assigned to vari-
ables of type char , byte , or short as long as the value being assigned can be represented
by the target type. An integer literal can always be assigned to a long variable.
Beginning with JDK 7, you can embed one or more underscores into an integer or
floating-point literal. Doing so can make it easier to read values consisting of many digits.
When the literal is compiled, the underscores are simply discarded. Here is an example:
This specifies the value 123,451,234. The use of underscores is particularly useful when
encoding things like part numbers, customer IDs, and status codes that are commonly
thought of as consisting of subgroups of digits.
Hexadecimal, Octal, and Binary Literals
As you may know, in programming it is sometimes easier to use a number system based
on 8 or 16 instead of 10. The number system based on 8 is called octal , and it uses the
digits 0 through 7. In octal the number 10 is the same as 8 in decimal. The base 16 number
system is called hexadecimal and uses the digits 0 through 9 plus the letters A through F,
which stand for 10, 11, 12, 13, 14, and 15. For example, the hexadecimal number 10 is 16
in decimal. Because of the frequency with which these two number systems are used, Java
allows you to specify integer literals in hexadecimal or octal instead of decimal. A hexa-
decimal literal must begin with 0x or 0X (a zero followed by an x or X). An octal literal
begins with a zero. Here are some examples:
Search WWH ::




Custom Search