Monday 27 June 2016

Underscores in Numeric Literals

In Java SE 7, any number of underscore characters (_) can appear anywhere between digits in a numerical literal.

This feature is used to separate groups of digits in numeric literals, which can improve the readability of your code.

Example:
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;

Important points:
We cannot place underscores in the following places:
1. At the beginning or end of a number
2. Adjacent to a decimal point in a floating point literal
3. Prior to an F or L suffix
4. In positions where a string of digits is expected.

Invalid Examples:
float pi1 = 3_.1415F;
float pi2 = 3._1415F;
long id = 999_99_9999_L;
int num = _42;
int num = 0_x54;
int num = 0x_52;
int num = 0x52_;
int num = 052_;

Valid Examples:
int num = 5_2;
int num = 5_______2;
int num = 0x5_2;
int num = 0_52; (octal literal) 

Example:
public class UnderscoresNumbers {
     public static void main(String[] args) {
           int a = 10_597;
           int b = 1_11_597;
          
           int sum = a+b;
          
           System.out.println("Sum is: "+ sum);
     }
}

Output:
     Sum is: 122194


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...