PREV NEXT
Literals:
Literal in Java represents constant value to be stored in variables. Literals are syntactic representations of boolean, character, numeric, or string data.
Example:
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 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.
Example:
int dec = 56;
int octal = 0164; int hex = 0x56; |
Floating Literals:
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.
Example:
double d = 153.6;
double temp = 1.534e2; //equals to 153.6 float num = 23.4f; |
Character Literals:
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.
Example:
char c = ‘a’;
char ch = ‘$’; char che = ‘5’; |
Escape Sequence:
Escape sequence | Meaning |
\n | New line |
\t | Tab |
\b | Backspace |
\r | Carriage return |
\f | Formfeed |
\\ | Backslash |
\’ | Single quotation mark |
\” | Double quotation mark |
\d | Octal |
\xd | Hexadecimal |
\ud | Unicode character |
Unicode Sequence | Meaning |
‘u0041’ | Capital letter A |
‘\u0030’ | Digit 0 |
‘\u0022’ | Double quote “ |
‘\u003b’ | Punctuation ; |
‘\u0020’ | Space |
‘\u0009’ | Horizontal Tab |
String Literals:
A set of characters form a string. String literals are represented within double quote.
Example:
String s = “hi”;
String s1 = “Hello!”; |
Boolean Literals:
Boolean literals contain only 2 values i.e true and false.
Example:
boolean flag = true;
boolean set = false; |
Null Literals:
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.