Sub topic 8
Writing Primitive Literals
A literal is a value written directly in Java code. For example, 3 is a whole-number literal, and true is a Boolean literal.
A variable is a named place to store a value. Its type tells Java what kind of value it can hold. Java has eight primitive types, which are built-in types for simple values.
Literals for the eight primitive types
| Type | Example literal | What it represents |
|---|---|---|
| `byte` | `10` | A small whole number |
| `short` | `1000` | A whole number |
| `int` | `3` | A whole number |
| `long` | `10000000000L` | A larger whole number |
| `float` | `20.5f` | A number with a decimal part |
| `double` | `19.99` | A number with a decimal part |
| `char` | `'A'` | One text unit |
| `boolean` | `true` | A true or false value |
A decimal whole-number literal such as 3 has type int by default. A small int literal can also be assigned to a byte or short variable if its value fits. Add L to write a long literal. Use a capital L because a lowercase l can look like the digit 1.
A literal such as 19.99 has type double by default. Add f to make a float literal, as in 20.5f.
Try a complete example
Save this program in a file named PrimitiveLiterals.java:
class PrimitiveLiterals {
public static void main(String[] args) {
byte small = 10;
short medium = 1000;
int count = 3;
long population = 10_000_000_000L;
float temperature = 20.5f;
double price = 19.99;
char grade = 'A';
boolean ready = true;
System.out.println(small);
System.out.println(medium);
System.out.println(count);
System.out.println(population);
System.out.println(temperature);
System.out.println(price);
System.out.println(grade);
System.out.println(ready);
}
}With Java installed, compile and run it from the folder containing the file:
javac PrimitiveLiterals.java
java PrimitiveLiteralsThe program prints the eight values, one per line. The underscores in 10_000_000_000L make the number easier to read. They do not change its value.
Other ways to write literals
For whole numbers, Java also accepts hexadecimal and binary literals. Hexadecimal uses base 16, and binary uses base 2. For example, 0x10 and 0b10000 both represent the decimal number 16.
A char literal uses single quotes, as in 'A'. A string is text that can contain many characters; a string literal uses double quotes, as in "A". Even though "A" contains one letter, it is not a char literal.
A char holds one UTF-16 code unit, a 16-bit piece used to represent text. Some characters, including many emoji, need two such units and cannot fit in one char.
An escape sequence is a way to write a special character using a backslash. For example, '\n' is a newline character.
The only boolean literals are true and false. Numbers such as 1 and 0 are not Boolean literals in Java.
Exercise
Which literals should you use to initialize a float with 2.5, a char with A, and a boolean with false?
Show answer
Use 2.5f for the float, 'A' for the char, and false for the boolean.