A literal is a value that can be written directly into a Java program. The compiler can calculate the value it represents because most primitive data types have their own literal pattern.Literal patterns:
- whole numbers are int values (e.g., 123).
- whole numbers followed by an "L" (or "l") are long values (e.g., 6720000000L). Note, long variables can be assigned a value using an int literal - a long literal is only needed when it is greater than the value an int data type can hold.
- decimal numbers are double values (e.g., 1.2) Note, you can also follow a decimal number with a "D" or "d" to explicitly define it as a double value.
- decimal numbers followed by an "F" or "f" are float values (e.g., 0.2F).
- truth values are boolean values (i.e., true, false).
- single characters in single quotes are character values (e.g., 'a').
- characters in double quotes are string values (e.g., "abc").
- whole numbers preceded by "0x" are hexadecimal numbers (e.g., 0xFF).
- whole numbers preceded by "0" are octal numbers (e.g., 0647).
Using literals to assign a value to an int variable. An int literal:
A hexadecimal literal:
int numOfDays = 7;
int hexNumber = 0x5F;