Literal in Java represents constant value to be stored in variables. Literals are syntactic representations of boolean, character, numeric, or string data.
|int var = 0;|
Here the value 0 is the literal which stores the value to the variable ‘var’. Each literal has a type associated with it such as int, char, float etc.
Literals are categorized into 5 major groups. They are,
- Integer Literals
- Floating Literals
- Character Literals
- String Literals
- Boolean Literals
Integer literal consists of the following types: byte, short, int, long. Integer literals can be expressed in decimal (base 10), hexadecimal (base 16) and binary (base 2) number systems. Prefix 0 is added to represent octal and prefix 0x is added to represent hexadecimal.
|int dec = 56;
int octal = 0164;
int hex = 0x56;
Floating point literals are like real numbers. There are 2 floating point types in java. i.e. float and double. The suffix D or d is appended to the value to designate the type as double and the suffix F or f is appended to designate the data as float. Floating point types can also be expressed using the E or e notation.
|double d = 153.6;
double temp = 1.534e2; //equals to 153.6
float num = 23.4f;
Char type uses 16 bit Unicode to store a character. We could specify the value of a character literal with a pair of single quote. A few special characters such as backslash, newline, quotation mark etc., can be specified using escape sequence. A special Unicode escape sequence can also be used to represent printable and non-printable characters.
|char c = ‘a’;
char ch = ‘$’;
char che = ‘5’;
|\’||Single quotation mark|
|\”||Double quotation mark|
|‘u0041’||Capital letter A|
|‘\u0022’||Double quote “|
A set of characters form a string. String literals are represented within double quote.
|String s = “hi”;
String s1 = “Hello!”;
Boolean literals contain only 2 values i.e true and false.
|boolean flag = true;
boolean set = false;
Null literal is specified as ‘null’. It is mostly used by reference type. It is used to indicate that the object is no longer available.
1. Ask your questions or clarify your/others doubts from,