Data
Literal
Java
boolean booleanVar = true;
int integerVar = 12;
double floatingPointVar = 1.618;
char charVar = 'c';
String stringVar = "Hello";
Object nullVar = null;
Literals represent values, like: true
, 12
or "Hello"
.
Literals in Java can be grouped into these categories:
- Boolean
- Integer
- Floating-point
- Character
- String
- Null
boolean enable = true;
boolean disable = false;
There are 2 Boolean literals, true
and false
.
int ans1 = 42; // Base10
int ans2 = 0b101010; // Binary
int ans3 = 052; // Octal
int ans4 = 0x2A; // Hexadecimal
long ans5 = 42L; // Long Base10
There are 5 Integer Literal representations:
- Base10
- Binary (base 2)
- Octal (base 8)
- Hexadecimal (base 16)
- Long
L
at the end of the ans5
value specifies that the value has long
precision.
You can also use underscores (_
) in your Integer literals for readability. So literals 42
, 4_2
and 4__2
are equal.
All the variables defined here are equal to value 42.
double pi1 = 3.14159; // Normal
double pi2 = 314159E-5; // Scientific
double pi3 = 3.14159D; // Double
float pi4 = 3.14159F; // Float
There are 4 Floating-point Literal representations:
- Normal
- Scientific
- Literal Double
- Literal Float
D
and F
at the end of the pi3
and pi4
values specify that these values have double
and float
precision.
If you don't specify D
or F
, the literal value is considered as double precision.
All the variables defined here are equal. (except pi4
, because of different precision between floats and doubles)
char FirstLetter = 'A';
A single letter can literally be specified using the character wrapped inside single quotes ('
).
String name = "Sam";
String is a sequence of characters.
A string can literally be specified using the sequence of characters wrapped inside double quotes ("
).