Underscores in Numeric Literals

In this section, you will learn about how you can use underscore in Numeric Literals in Java SE 7.

Underscores in Numeric Literals

In this section, you will learn about how you can use underscore in Numeric Literals in Java SE 7.

Underscores in Numeric Literals

Underscores in Numeric Literals

In this section, you will learn about how you can use underscore in Numeric Literals in Java SE 7.

In Java SE 7,  You can place any number of underscore( _ ) between digits of numeric literals. This added feature improves the readability of the code. For example : Using underscore you can separate groups of digits in numeric literals . For Example credit card number can be write as follows :

long creditCardNumber = 1234_5678_9012_3456L;

You can place underscore between digits. But for placing underscore you need to be careful. You can't place underscore in the following places :

  • You can't place it at the beginning or at the end of a number.

  • Adjacent to a decimal point in a floating point literal.

  • Before to an F or L suffix.

  • In positions where a string of digits is expected.

Some of the valid example with different type of data type is given below :

  • long creditCardNumber = 1234_5678_9012_3456L;
  • long socialSecurityNumber = 999_99_9999L;
  • float pi = 3.14_15F;
  • long hexBytes = 0xFF_EC_DE_5E;
  • long hexWords = 0xCAFE_BABE;
  • long maxLong = 0x7fff_ffff_ffff_ffffL;
  • byte nybbles = 0b0010_0101;
  • long bytes = 0b11010010_01101001_10010100_10010010;

Some of the invalid examples are given below :

  • float pi1 = 3_.1415F;
  • float pi2 = 3._1415F;
  • long socialSecurityNumber1= 999_99_9999_L;
  • int x3 = 52_;
  • int x5 = 0_x52;
  • int x6 = 0x_52;
  • int x8 = 0x52_;
  • int x11 = 052_;