Underscores in Numeric Literals for Readability
You'll learn how to use underscores to make large numbers easier to read in your Java code.
The Problem with Large Numbers
When you write large numbers in code, they can be hard to read at a glance. Is 1000000 one million or ten million? You have to count the zeros carefully, which is error-prone and time-consuming.
The Solution: Underscores as Visual Separators
Java allows you to insert underscores (_) between digits in numeric literals to improve readability. Think of them like the commas we use in everyday writing (1,000,000), except Java uses underscores instead.
int populationIndia = 1_400_000_000; // Much clearer than 1400000000
long distanceToMoon = 384_400L; // 384,400 kilometers
double accountBalance = 12_345.67; // Works with floating-point too
int hexColor = 0xFF_EC_DE; // Even in hexadecimal!
int binary = 0b1010_1100_0011; // And binary literals
The underscores are completely ignored by the compiler—they're purely for human readers. You can place them wherever makes sense to you, though typically every three digits (like thousands separators) is most common.
Rules to Remember
- You cannot start or end a number with an underscore:
_123or123_are illegal - You cannot place underscores next to the decimal point:
12_.34or12._34won't work - You cannot place underscores before suffixes:
123_Lis invalid (use123Lor12_3L)
Key Takeaway: Use underscores between digits in numeric literals to make large numbers readable—they're ignored by the compiler but help humans understand your code quickly.