Rules and Restrictions for Underscores in Literals
What you'll learn: Where you can and cannot place underscores in numeric literals to keep your code compilable.
In the previous lesson, you learned that underscores improve readability in numeric literals. But Java has strict rules about where these underscores can appear—break them, and your code won't compile.
Where Underscores Are Allowed
You can place underscores between digits in any numeric literal:
int valid1 = 1_000_000; // Between decimal digits
long valid2 = 0xFF_EC_DE_5E; // Between hexadecimal digits
int valid3 = 0b0010_1101; // Between binary digits
double valid4 = 123_456.789_012; // In both integer and fractional parts
Where Underscores Are FORBIDDEN
Underscores cannot appear:
-
At the beginning or end of a number:
int bad1 = _123; // Compilation error! int bad2 = 123_; // Compilation error! -
Adjacent to a decimal point:
double bad3 = 3_.14; // Compilation error! double bad4 = 3._14; // Compilation error! -
Before an F, D, or L suffix:
long bad5 = 123_L; // Compilation error! float bad6 = 1.5_F; // Compilation error! -
In positions where a string of digits is expected (like after 0x or 0b prefixes):
int bad7 = 0_x52; // Compilation error! int bad8 = 0x_52; // Compilation error!
Think of it like punctuation in writing: you wouldn't put a comma at the beginning or end of a sentence, or right next to a period. Underscores are meant to separate groups of digits, not replace actual numbers or syntax elements.
Key Takeaway: Underscores in numeric literals must appear strictly between digits—never at boundaries, next to decimal points, before suffixes, or adjacent to base prefixes.