Java Literals: Integer, Floating-Point, char and boolean
Introduction
When you write
(Note - Literals are values of the types described in Java Primitive Data TypesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples, which is worth reading first.) Integer literals A whole number written in code is an integer literal, and its type is
Integer literals can be written in four number systems, identified by their prefix -
OUTPUT of the above code
Explanation of the code
Floating-point literals
A number with a decimal point or an exponent is a floating-point literal. Its type is
OUTPUT of the above code
Notice that Java prints very small and very large
boolean, String and null literals
OUTPUT of the above code
Explanation of the code
OUTPUT of the above code
2. Forgetting the L or f suffix. A number too large for an
OUTPUT on compiling the above code
OUTPUT on compiling the above code
Adding the suffixes -
int count = 42;, the 42 is a literal - a fixed value written directly in the source code. This tutorial explains Java literals of every kind, with examples. We will start with integer literals, including hexadecimal, octal and binary numbers, and underscores which make long numbers readable. We will then look at floating-point literals, character literals and escape sequences, and boolean, string and null literals. Lastly, we will look at the mistakes with literals that most often trip up beginners.(Note - Literals are values of the types described in Java Primitive Data TypesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples, which is worth reading first.) Integer literals A whole number written in code is an integer literal, and its type is
int unless it ends with L or l, which makes it a long. Always use a capital L - a lower-case l looks too much like the digit 1.Integer literals can be written in four number systems, identified by their prefix -
- Decimal (base 10): no prefix -
255. - Hexadecimal (base 16): prefix
0xor0X, digits 0-9 and A-F -0xFF. Common for colors, memory addresses and bit masks. - Binary (base 2): prefix
0bor0B, digits 0 and 1 -0b1111_1111. - Octal (base 8): prefix
0(zero), digits 0-7 -0377. Rarely used - and a common source of bugs, as we will see.
1_000_000 is the same as 1000000. They cannot be placed at the start or end of a number, or next to a decimal point, a prefix or a suffix.
Integer literals in different number systems
//IntegerLiterals.java
public class IntegerLiterals {
public static void main(String[] args) {
int decimal = 255;
int hex = 0xFF;
int binary = 0b1111_1111;
int octal = 0377;
System.out.println("decimal = " + decimal + ", hex = " + hex + ", binary = " + binary + ", octal = " + octal);
int population = 1_428_627_663;
long worldPopulation = 8_100_000_000L;
int creditCardGroup = 1234_5678;
System.out.println("population = " + population + ", world = " + worldPopulation + ", group = " + creditCardGroup);
int color = 0xFF_8C_00; // red, green and blue bytes of a dark orange color
System.out.println("color = " + color + " = 0x" + Integer.toHexString(color).toUpperCase());
}
}
decimal = 255, hex = 255, binary = 255, octal = 255 population = 1428627663, world = 8100000000, group = 12345678 color = 16747520 = 0xFF8C00
255,0xFF,0b1111_1111and0377are four ways of writing the same number. Java stores the value, not the way it was written, so all four print as255.8_100_000_000Lneeds theL, because it is larger than the biggestint.Integer.toHexString()converts a number back to hexadecimal text.
double, unless it ends with f or F, which makes it a float. (A d or D suffix is also allowed for double, but rarely needed.)- Ordinary decimal form -
3.14,0.5,.5,10.0. - Scientific notation, with
eorEmeaning "times 10 to the power of" -1.5e3is 1500.0, and2.5e-4is 0.00025. - A whole number with an
fordsuffix is also floating-point -10fis10.0f.
Floating-point literals
//FloatingLiterals.java
public class FloatingLiterals {
public static void main(String[] args) {
double pi = 3.14159;
float rate = 4.5f;
double distance = 1.5e3; // 1.5 x 10^3
double tiny = 2.5e-4; // 2.5 x 10^-4
double avogadro = 6.022e23;
float ten = 10f;
double million = 1_000_000.0;
System.out.println(pi + " " + rate + " " + distance + " " + tiny);
System.out.println(avogadro + " " + ten + " " + million);
}
}
3.14159 4.5 1500.0 2.5E-4 6.022E23 10.0 1000000.0
double values in scientific notation itself - 2.5E-4 and 6.022E23 - while values in between, such as 1000000.0, are printed in ordinary form. To control how numbers are printed, use printf and String.formatClick to read tutorial: Java Console Output: println, printf and String.format.
Character literals and escape sequences
A character literal is a single character in single quotes, of type char - 'A', 'z', '7', '@'. Characters which cannot be typed directly, or which have a special meaning, are written with an escape sequence starting with a backslash -\n- new line;\t- tab;\r- carriage return.\'- single quote;\"- double quote;\\- backslash.\b- backspace;\f- form feed;\s- space (since Java 15, mainly for text blocks).\uXXXX- any Unicode character, by its four-digit hexadecimal code.'\u0041'is'A', and'\u20B9'is the Indian Rupee sign.
- boolean literals: just two -
trueandfalse. - String literals: text in double quotes, such as
"Hello"or the empty string"". A string literal is an object of the classString. Since Java 15, text blocks - enclosed in"""- allow string literals over several lines; see Java Text BlocksClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples. - The null literal:
nullmeans "no object". It can be assigned to any reference type variable, such as aString, but not to a primitive.
Character, boolean, string and null literals
//OtherLiterals.java
public class OtherLiterals {
public static void main(String[] args) {
char letter = 'J';
char quote = '\'';
char rupee = '\u20B9';
boolean isJavaFun = true;
String path = "C:\\Users\\Tom";
String dialog = "She said \"Hello\"";
String nothing = null;
System.out.println(letter + " " + quote + " " + (int) rupee + " " + isJavaFun);
System.out.println(path);
System.out.println(dialog);
System.out.println("Name:\tTom\nCity:\tLondon");
System.out.println("nothing = " + nothing);
}
}
J ' 8377 true C:\Users\Tom She said "Hello" Name: Tom City: London nothing = null
'\''is a single quote character, and"C:\\Users\\Tom"uses\\for each backslash in a Windows path.(int) rupeeprints the Rupee sign's Unicode number, 8377 (hexadecimal 20B9). Whether the character itself displays depends on your console's font and encoding.\tinserted tabs and\nstarted a new line, so oneprintln()printed two aligned lines.- Joining
nullto a string prints the wordnull.
010 to line up numbers gives 8, not 10 - and 09 does not compile at all, because 9 is not an octal digit.
A leading zero changes the value
//LeadingZero.java
public class LeadingZero {
public static void main(String[] args) {
int a = 010;
int b = 10;
System.out.println("010 = " + a + ", 10 = " + b);
}
}
010 = 8, 10 = 10
int needs L, and a decimal number assigned to a float needs f - otherwise the code does not compile.
A long literal without the L suffix
//MissingL.java
public class MissingL {
public static void main(String[] args) {
long big = 8100000000;
}
}
MissingL.java:4: error: integer number too large
long big = 8100000000;
^
1 error
A float variable given a double literal
//MissingF.java
public class MissingF {
public static void main(String[] args) {
float price = 9.99;
}
}
MissingF.java:4: error: incompatible types: possible lossy conversion from double to float
float price = 9.99;
^
1 error
8100000000L and 9.99f - fixes both errors.
3. Mixing up quotes. 'A' is a char, while "A" is a String. Single quotes must contain exactly one character, so 'AB' is a compile error.
Summary
In this tutorial we first looked at integer literals in decimal, hexadecimal, binary and octal, the L suffix for long, and underscores for readability. We then looked at floating-point literals in decimal and scientific notation, and the f suffix for float. Next we saw character literals and escape sequences, and then boolean, string and null literals. Lastly, we went through common mistakes - the octal leading zero, missing suffixes and mixed-up quotes. In the next tutorial, we will see how values are converted from one type to another with type conversion and castingClick to read tutorial: Type Conversion and Casting in Java with Examples.Java Fundamentals Tutorials
Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java var Keyword: Local Variable Type InferenceClick to read tutorial: Java var Keyword: Local Variable Type Inference Java Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators Java Bitwise and Shift Operators with ExamplesClick to read tutorial: Java Bitwise and Shift Operators with Examples
Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java var Keyword: Local Variable Type InferenceClick to read tutorial: Java var Keyword: Local Variable Type Inference Java Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators Java Bitwise and Shift Operators with ExamplesClick to read tutorial: Java Bitwise and Shift Operators with Examples