Index
Java Literals
Literals are data used for representing fixed values.
Boolean Literals
In Java, boolean literals are used to initialise boolean data types. They can store two values: true and false.
boolean flag1 = false;
boolean flag2 = true;
Here, false
and true
are two boolean literals.
Integer Literals
An integer literal is a numeric value (associated with numbers) without any fractional or exponential part.
There are 4 types of integer literals in Java:
- binary (base 2)
- decimal (base 10)
- octal (base 8)
- hexadecimal (base 16)
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;
// decimal
int decNumber = 34;
// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
// binary
int binNumber = 0b10010; // 0b represents binary
Tip
Integer literals are used to initialize variables of integer types like
byte
,short
,int
, andlong
.
Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponential form.
class Main {
public static void main(String[] args) {
double aDouble = 3.4;
float aFloat = 3.4F;
// 3.445*10^2
double aDoubleScientific = 3.445e2;
System.out.println(aDouble); // prints 3.4
System.out.println(aFloat); // prints 3.4
System.out.println(aDoubleScientific); // prints 344.5
}
}
Tip
The floating-point literals are used to initialize
float
anddouble
type variables.
Character Literals
Character literals are Unicode character enclosed inside single quotes.
char letter = 'a';
Here, a
is the character literal.
Tip
We can also use Escaping Sequences as character literals. For example, \b (backspace), \t (tab), \n (new line), etc.
String literals
A string literal is a sequence of characters enclosed inside double-quotes.
String str1 = "Java Programming";
String str2 = "Ciao Mamma";
Here, Java Programming
and Ciao Mamma
are two string literals.