Java Reference
In-Depth Information
Integer literals can be specified in the decimal, hexadecimal, octal, and binary
formats:
• The decimal format is the default format; for example,
127
.
• Thehexadecimalformatrequiresthattheliteralbeginwith
0x
or
0X
andcon-
tinue with hexadecimal digits (
0
-
9
,
A
-
F
,
a
-
f
); for example,
0x7F
.
• The octal format requires that the literal be prefixed with
0
and continue with
octal digits (
0
-
7
); for example,
0177
.
• Thebinaryformatrequiresthattheliteralbeprefixedwith
0b
or
0B
andcon-
tinue with
0
s and
1
s; for example,
0b01111111
.
To improve readability, you can insert underscores between digits; for example,
204_555_1212
.Althoughyoucaninsertmultiplesuccessiveunderscoresbetweendi-
gits (as in
0b1111__0000
), you cannot specify a leading underscore (as in
_123
)
becausethecompilerwouldtreattheliteralasanidentifier.Also,youcannotspecifya
trailing underscore (as in
123_
). A
floating-point literal
consists of an integer part, a
decimal point (represented by the period character [
.
]), a fractional part, an exponent
(starting with letter
E
or
e
), and a type suffix (letter
D
,
d
,
F
, or
f
). Most parts are op-
tional,butenoughinformationmustbepresenttodifferentiatethefloating-pointliteral
from an integer literal. Examples include
0.1
(double precision floating-point),
89F
(floating-point),
600D
(doubleprecisionfloating-point),and1
3.08E+23
(doublepre-
cisionfloating-point).Aswithintegerliterals,youcanmakefloating-pointliteralseasier
to read by placing underscores between digits (
3.141_592_654
, for example).
Finally,the
null
literalisassignedtoareferencevariabletoindicatethatthevariable
does not refer to an object.
The following examples use literals to initialize the previously presented variables:
int counter = 10;
double temperature = 98.6; // Assume Fahrenheit scale.
String firstName = "Mark";
int[] ages = { 52, 28, 93, 16 };
char gradeLetters[] = { 'A', 'B', 'C', 'D', 'F' };
float[][] matrix = { { 1.0F, 2.0F, 3.0F }, { 4.0F, 5.0F,
6.0F }};
int x = 1, y[] = { 1, 2, 3 }, z = 3;
Thelastfourexamplesusearrayinitializerstoinitializethe
ages
,
gradeletters
,
matrix
, and
y
arrays. An
array initializer
consists of a brace-and-comma-delimited