In Java, literals are specific values that are directly used in the code, and they represent constant values. Java literals can be categorized into several types based on the kind of data they represent. Here’s a breakdown of the different types of literals in Java:
1. Integer Literals
These are whole numbers without any fractional or decimal part. Integer literals can be represented in various numeral systems:
- Decimal (base 10): e.g.,
123
,0
,-456
- Hexadecimal (base 16): prefixed with
0x
or0X
, e.g.,0x7F
,0xFF
,0xA
- Octal (base 8): prefixed with
0
, e.g.,075
,012
- Binary (base 2): prefixed with
0b
or0B
, e.g.,0b1010
,0b1100
2. Floating-Point Literals
These represent numbers with a fractional part and are of type float
or double
. They can be expressed in:
- Decimal notation: e.g.,
3.14
,0.0
,-2.71828
- Scientific notation: using
e
orE
to denote powers of 10, e.g.,1.23e4
(which is1.23 × 10^4
),2.5E-3
(which is2.5 × 10^-3
)
3. Character Literals
These represent single characters and are enclosed in single quotes. Examples include:
'a'
,'A'
,'9'
,'$'
,'\n'
(newline),'\u0041'
(Unicode representation of ‘A’)
4. String Literals
These represent sequences of characters and are enclosed in double quotes. Examples include:
"Hello, World!"
,"123"
,""
(an empty string)
5. Boolean Literals
These represent the boolean values and are true
or false
.
6. Null Literal
The null
literal represents a null reference and is used to indicate that a variable does not point to any object or value.
Each type of literal serves a specific purpose and helps in representing and manipulating data in Java programs.
Leave a Reply