This article explains Java literals. If you don’t know why float pi = 3.14 fails to compile, this article is a must read for you.
What are literals
Any value used directly in Java code is a literal. I have marked literals in the code below with bold text, so you can get a better idea what a literal is:
int num = 123; // int literal double num2 = 123.45; // double literal int result = 16 - 5; // two int literals int otherResult = result * 5; // only one literal: 5; "result" is a variable String str = "string literal"; // String literal char letter = 'a'; // char literal
Data type of a literal depends on the way it is written. In example, “abc” represents String literal, while 123 represents int literal and 123.45 represents double literal.
In this article I want to show how to write literals that represent various Java data types.
Int literals are written as plain integer numbers.
Long literals are written as integer numbers with L suffix.
The case of letter L doesn’t matter, but it is recommended to use uppercase L because in some fonts lowercase L looks like number 1.
long num1 = 123456789L; long num2 = 123456789l; int num3 = 123l; // compilation error - can't assign long to int
Float literals are written as floating-point numbers with F suffix. The case of letter F doesn’t matter.
Double literals are written as plain floating-point numbers. Optionally suffix D (case doesn’t matter) can be provided.
double num1 = 3.14; double num2 = 2.71d; float tricky = 123.45; // fails to compile - can't assign double to float
String literals are enclosed within double quotes.
Char literals are enclosed within single quotes.
You can specify a character directly or as a UTF-16 code point (\u prefix and hex value).
char ch1 = 'a'; char ch2 = 'π'; // you can enter UTF-16 characters directly char ch3 = '\u03C0'; // ...or as code points, here for U+03C0 (π)
Hexadecimal literals are hexadecimal numbers with 0x prefix.
Those literals represent numbers in hexadecimal system (base-16).
Binary literals are binary numbers with 0b prefix.
Those literals represent numbers in binary system (base-2).
Octal literals are octal numbers with 0 prefix.
Those literals represent numbers in octal system (base-8).
You can write numbers in exponential notation by using letter e to denote exponent.
Numbers in exponential notation have type of double.
You can write hexadecimal numbers in exponential notation by using 0x prefix and using p to denote exponent.
Exponent is written as a decimal number, and exponent base is 2.
underscores in numeric literals
Numeric literals can be formatted using underscores. The underscores in numeric literals are ignored by compiler – their only function is increase of code readability.
Learn more about Java