A literal is any term that directly represents a value in the code. Examples of literals are
X = 5; Str = "Test";
Table 7.6 shows a series of special cases that demonstrate the rules to follow when you want to use numeric literal values in your Java program, along with the values to use with Boolean variables.
Table 7.6 Examples of Numeric/Boolean Literals
Example | Description |
---|---|
123 | Integer value literal |
123L | Long value literal |
0123 | Octal literal, prefix literal with a 0 |
0x123 | Hexadecimal literal, prefix literal with 0x |
12.3F | Floating-point literal |
12.3 | Double literal |
12.3e12 | Double literal with exponents |
true | Boolean 'True' literal value |
false | Boolean 'False' literal value |
Compared to numeric literals, character and string literals are a little more complicated. A character literal is a single character that is enclosed in single quotes. A string literal is enclosed in double quotes. A string literal can contain any of the character literals that are described in Table 7.7.
Table 7.7 Special Character Literal Symbols
Code | Description |
---|---|
\n | New line |
\\ | Backslash character |
\t | Tab |
\b | Backspace |
\r | Carriage return |
\f | Form feed |
\' | Single quotation |
\' | Double quotation |
\val | If val is a number, it is interpreted as octal |
An example of a string literal with embedded characters follows.
String str = "This\nis\na test\nof the \\n\nliteral";
If the preceding variable is printed, the output will look something like this:
This Is A test Of the \n literal
Team-Fly |