Literal Values for Primitive Types
A primitive literal is merely a source code representation of the primitive data types.
Integer Literals
There are three ways to represent integer numbers in Java language:
- Decimal (base 10)
- Octal (base 8)
- Hexadecimal (base 16)
All three integer literals are defined as int by default, but they may also be specified as long by placing a suffix of L or l after the number.
Decimal Literals
Integer values that are represented as is, with no prefix of any kind.
class Decimal {
public static void main(String[] args) {
int seven = 7;
int sixtyNine = 69;
System.out.println(seven);
System.out.println(sixtyNine);
}
}
Octal Literals
- In Java, we represent an integer in octal form by placing a zero in front of the number.
- We can have up to 21 digits in an octal number, not including the leading zero.
Hexadecimal Literals
- Java will accept capital or lowercase letters for the alphabetic characters (one of the few places Java is not case-sensitive).
- We are allowed up to 16 digits in a hexadecimal number, not including the prefix 0x or the optional suffix extension L.
Floating-Point Literals
- Floating-point numbers are defined as a number, a decimal symbol, and more numbers representing the fraction.
- Floating-point literals are defined as double (64 bits) by default, so if we want to assign a floating-point literal to a variable of type float (32 bits), we must attach the suffix F or f to the number.
- We may also optionally attach a D or d to double literals, but it is not necessary because this is the default behavior.
Boolean Literals
- A boolean value can be defined as true or false.
- Although in C (and some other languages) it is common to use numbers to represent true or false, this will not work in Java.
Character Literal
- A char literal is represented by a single character in single quotes.
- We can also type in the Unicode value of the character, using the Unicode notation of prefixing the value with \u.
- We can assign a number literal, assuming it will fit into the unsigned 16-bit range (65535 or less).
- We can also use an escape code if we want to represent a character that can't be typed in as a literal.
Literal Values for Strings
- A string literal is a source code representation of a value of a String object.
- Strings are not primitive.
Comments
Post a Comment