Underscores in Numeric Literals
Let’s see underscores in numeric literals in action:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.journaldev.util; public class UnderscoreNumericLiterals { public static void main(String[] args) { long ccNumber = 1234_5678_9012_3456L; long ssn = 999_99_9999L; float pi = 3.14_15F; long hexadecimalBytes = 0xFF_EC_DE_5E; long hexadecimalWords = 0xCAFE_BABE; long maxOfLong = 0x7fff_ffff_ffff_ffffL; byte byteInBinary = 0b0010_0101; long longInBinary = 0b11010010_01101001_10010100_10010010; int add = 12_3 + 3_2_1; System.out.println("ccNumber="+ccNumber); System.out.println("ssn="+ssn); System.out.println("pi="+pi); System.out.println("hexadecimalBytes="+hexadecimalBytes); System.out.println("hexadecimalWords="+hexadecimalWords); System.out.println("maxOfLong="+maxOfLong); System.out.println("byteInBinary="+byteInBinary); System.out.println("longInBinary="+longInBinary); System.out.println("add="+add); } } |
The above program compiles fine and here is the output:
1 2 3 4 5 6 7 8 9 10 11 |
<span style="color: #008000;"><strong><code> ccNumber=1234567890123456 ssn=999999999 pi=3.1415 hexadecimalBytes=-1253794 hexadecimalWords=-889275714 maxOfLong=9223372036854775807 byteInBinary=37 longInBinary=-764832622 add=444 </code></strong></span> |
Tips for Underscores in Numeric Literals
- Underscores can be placed only between digits.
- You can’t put underscores next to decimal places, L/F suffix or radix prefix. So 3._14, 110_L, 0x_123 are invalid and will cause compilation error.
- Multiple underscores are allowed between digits, so 12___3 is a valid number.
- You can’t put underscores at the end of literal. So 123_ is invalid and cause compile time error.
- When you place underscore in the front of a numeric literal, it’s treated as an identifier and not a numeric literal. So don’t confuse with it.
1234int _10=0;int x = _10; - You can’t use underscores where you are expecting a String with digits. For example
Integer.parseInt("12_3");
will throwjava.lang.NumberFormatException
.