Java Glossary : literals
Last updated 2004-06-28 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java
Glossary : L words : literals.
- literals
-
A literal is an explicit number or string constant used in Java programs. Here
is a list of all the variant forms I have found Java to support:
-
int
1, -1, hex ints 0x0f28,
unicode hex '\u003f', octal 027,
Integer.MAX_VALUE (2,147,483,647), Integer.MIN_VALUE
(-2,147,483,648)
Beware! A lead 0 on an integer implies OCTAL. That was a major design blunder
inherited from C, guaranteed to introduce puzzling bugs. Be especially careful
when specifying months or days, where you naturally tend to provide a lead 0.
-
byte / short
There is no such thing as a byte or short literal. You would have to write it
with a cast e.g. (byte)0xff or (short)-99.
-
long
3L, -99l, 0xf011223344L
(Beware! some compilers will just chop the high bits from literals without the
trailing L even when assigning to a long.), Long.MAX_VALUE
(9,223,372,036,854,775,807), Long.MIN_VALUE (-9,223,372,036,854,775,808).
-
float
1.0345F, 1.04E-12f, .0345f,
1.04e-13f, Float.NaN.
-
double
5.6E-120D, 123.4d, 0.1,
Double.NaN, Math.PI.
Note floating point literals without the explicit trailing f, F, d or D are
considered double. In theory you don't need a lead 0, e.g. 0.1d
may be written .1d, though the Solaris and Symantec
compilers seem to require it.
-
boolean
true and false.
-
String
"ABC", enclosed in double quotes. You may
not split strings over two lines. If you must, code like this:
String s = "abc"
+ "def";
There is no speed penalty for the + concatenation. It
is done at compile time. String literals can be used anywhere you might use a
String reference. e.g. "abc".charAt(1)
is legal. For problematic characters like embedded ",
see escape sequences below.
-
char
'A', enclosed in single quotes, or integer forms e.g.
(char)45, (char)0x45, '\u003f'.
For problematic characters like embedded ', see
escape sequences below.
-
Escape sequences
inside char and string literals include:
'\u003f' unicode hex, (must be exactly 4 digits)
'\n' newline, ctrl-J (10, x0A)
'\b' backspace, ctrl-H (8, 0x08)
'\f' formfeed, ctrl-L (12, 0x0C)
'\r' carriage return, ctrl-M (13, 0x0D)
'\t' tab, ctrl-I (9, 0x09)
'\\' backslash,
'\'' single quote (optional inside " "),
'\"' double quote (optional inside ' '),
'\377' octal (must be exactly 3 digits. You can get
away with fewer, but then you create an ambiguity if the character following the
literal just happens to be in the range 0..7.)
\007 bel, ctrl-G (7, 0x07)
\010 backspace, ctrl-H (8, 0x08)
\013 vt vertical tab, ctrl-K (11, 0x0B)
\032 sub, eof, ctrl-Z (26, 0x1A)
-
Unsupported
There is no Pascalian '#nnn' style way of specifying
decimal constants. Just use char c = 123;
The following C forms are not supported: '\a'
alert
'\v' vertical tab
'\?' question mark
'\xf2' hex. Use the unicode \uffff form for
printable characters.