Underscores in Numeric Literals – Java 7 Feature


One of the Java 7 highlights is underscores in numeric literals. You can put underscores between digits of any numeric exacting like int, byte, short, skim, long, twofold. Utilizing underscores in numeric literals will enable you to separate them into gatherings for better readability.

Underscores in Numeric Literals

Let's see underscores in numeric literals in action:

Copy
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:

Copy
ccNumber=1234567890123456 ssn=999999999 pi=3.1415 hexadecimalBytes=-1253794 hexadecimalWords=-889275714 maxOfLong=9223372036854775807 byteInBinary=37 longInBinary=-764832622 add=444

Tips for Underscores in Numeric Literals

  • Underscores can be set just between digits.
  • You can't put underscores by decimal spots, L/F addition or radix prefix. So 3._14, 110_L, 0x_123 are invalid and will cause gathering error.
  • Multiple underscores are permitted between digits, so 12___3 is a legitimate number.
  • You can't put underscores toward the finish of exacting. So 123_ is invalid and cause order time error.
  • When you place underscore in the front of a numeric strict, it's treated as an identifier and not a numeric exacting. So don't mistake for it.
    Copy
    int _10=0; int x = _10;
  • You can't utilize underscores where you are anticipating a String with digits. For instance Integer.parseInt("12_3"); will toss java.lang.NumberFormatException.





© Journaldev Python 3 tutorial spring tutorial