A constant value in a program is denoted by a
literal. Literals represent numerical (integer or floating-point), character, boolean or string values.
Example of literals:Integer literals:
33 0 -9
Floating-point literals:
.3 0.3 3.14
Character literals:
'(' 'R' 'r' '{'
Boolean literals:(predefined values)
true falseString literals:
"language" "0.2" "r" ""Note: Three reserved identifiers are used as predefined literals:
true and false representing boolean values.
null representing the null reference.
Let's have a closer look at our literals and type of data they can represent: Integer Literals
Integer data types consist of the following
primitive data types:
int,long, byte, and short.
int is the default data type of an integer literal.
An integer literal, let's say 3000, can be specified as long by appending the suffix L (or l) to the integer value: so 3000L (or 3000l) is interpreted as a long literal.
There is no suffix to specify short and byte literals directly; 3000S , 3000B, 3000s, 3000b
Floating-point Literals
Floating-point data consist of
float and
double types.
The default data type of floating-point literals is
double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.
We can also specify a floating-point literal in scientific notation using Exponent (short E or e), for instance: the double literal 0.0314E2 is interpreted as
0.0314 *10²
(i.e 3.14).
Examples of double literals:
0.0 0.0D 0d
0.7 7D .7d
9.0 9. 9D
6.3E-2 6.3E-2D 63e-1
Examples of float literals:
0.0f 0f 7F .7f
9.0f 9.F 9f
6.3E-2f 6.3E-2F 63e-1f
Note: The decimal point and the exponent are both optional and at least one digit must be specified.
Boolean Literals
As mentioned before,
true and
false are reserved literals representing the truth-values
true and
false respectively. Boolean literals fall under the primitive data type:
boolean.
Character Literals
Character literals have the primitive data type character.
A character is quoted in single quote (
').
Note: Characters in Java are represented by the 16-bit Unicode character set. String Literals
A string literal is a sequence of characters which has to be double-quoted (") and occur on a single line.
Examples of string literals:"false or true"
"result = 0.01"
"a"
"Java is an artificial language"
String literals are objects of the class String, so all string literals have the type String.