JB Header

Java Literals: Integer, Floating-Point, char and boolean

Introduction When you write 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 0x or 0X, digits 0-9 and A-F - 0xFF. Common for colors, memory addresses and bit masks.
  • Binary (base 2): prefix 0b or 0B, 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.
Underscores can be placed between digits to make long numbers easier to read - 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());
  }
}
 OUTPUT of the above code
decimal = 255, hex = 255, binary = 255, octal = 255
population = 1428627663, world = 8100000000, group = 12345678
color = 16747520 = 0xFF8C00
Explanation of the code
  • 255, 0xFF, 0b1111_1111 and 0377 are four ways of writing the same number. Java stores the value, not the way it was written, so all four print as 255.
  • 8_100_000_000L needs the L, because it is larger than the biggest int.
  • Integer.toHexString() converts a number back to hexadecimal text.
Floating-point literals A number with a decimal point or an exponent is a floating-point literal. Its type is 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 e or E meaning "times 10 to the power of" - 1.5e3 is 1500.0, and 2.5e-4 is 0.00025.
  • A whole number with an f or d suffix is also floating-point - 10f is 10.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);
  }
}
 OUTPUT of the above code
3.14159 4.5 1500.0 2.5E-4
6.022E23 10.0 1000000.0
Notice that Java prints very small and very large 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.
The same escape sequences work inside string literals.
boolean, String and null literals
  • boolean literals: just two - true and false.
  • String literals: text in double quotes, such as "Hello" or the empty string "". A string literal is an object of the class String. 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: null means "no object". It can be assigned to any reference type variable, such as a String, 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);
  }
}
 OUTPUT of the above code
J ' 8377 true
C:\Users\Tom
She said "Hello"
Name:	Tom
City:	London
nothing = null
Explanation of the code
  • '\'' is a single quote character, and "C:\\Users\\Tom" uses \\ for each backslash in a Windows path.
  • (int) rupee prints the Rupee sign's Unicode number, 8377 (hexadecimal 20B9). Whether the character itself displays depends on your console's font and encoding.
  • \t inserted tabs and \n started a new line, so one println() printed two aligned lines.
  • Joining null to a string prints the word null.
Common mistakes with literals 1. A leading zero makes a number octal. Writing 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);
  }
}
 OUTPUT of the above code
010 = 8, 10 = 10
2. Forgetting the L or f suffix. A number too large for an 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;
  }
}
 OUTPUT on compiling the above code
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;
  }
}
 OUTPUT on compiling the above code
MissingF.java:4: error: incompatible types: possible lossy conversion from double to float
    float price = 9.99;
                  ^
1 error
Adding the suffixes - 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.