In this tutorial you will learn about the Java Literals and its application with practical example.
Java Literals
Literals are used to express certain fixed values within the source code of the program. They are used to represent a value directly in the code without any computation. Java literals can be assigned to any primitive type variable.
Example:-
1 |
boolean flg = false; |
Here,
boolean:- is a data type.
flg:- – is variable
false:- is literal.
In Java, literals can be used to represent the value of an integer, floating-point number, or string type. Here are some valid literals examples –
1 2 3 |
15 // Integer literal 10.3959 // Floating-point literal "Hello, world!" // String literal |
In Java, literals can be of following types –
Integer Literals
Integer literals are used to represent a decimal, binary, or hexadecimal value. Integer literals are used to initialize variables of integer data types byte, short, int, and long. Integer literal that ends with l or L is of type long. In Java, a binary literals starts with 0b, and hexadecimal literal starts with 0x, and the rest of every integer literal is a decimal literal.
Example:-
1 2 3 |
int decInt = 18 // 18 in decimal notation int binInt = 0b10010 // 18 in binary notation int hexInt = 0x12 // 18 in hexadecimal notation |
Floating-point Literals
A floating-point literal is used to represent the value for a float and double variable or constants. A decimal floating-point literal is composed of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both. If a floating-point literal ends with f or F, it’s of type float. Otherwise, it’s of type double. A double type can optionally end with D or d. They can also be expressed in scientific notation using E or e.
Example1:-
1 2 3 |
double myDouble = 3.4; float myFloat = 3.4F; double myDoubleScientific = 3.445e2; |
String & Character literals
String literals are represented as a sequence of characters surrounded by double quotes and a character literal is represented as a single character surrounded by single quotes. Java also allows the use of escape sequences in string and character literals. For example, \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \” (double quote), \’ (single quote), and \\ (backslash).
Example:-
1 2 3 |
char myChar = 'A'; char newLine = '\n'; String myString = "W3Adda Java Tutorial"; |
Here, ‘A’ is a character literal, and “W3Adda Java Tutorial” is a string literal.
Boolean Literals
Boolean literals are used to represent true and false value.
Example:-
1 |
boolean flg = true; |
Here, true is a boolean literal which is assigned to the variable flg.