Sunday, 21 December 2014

USING UNDERSCORES IN NUMERIC LITERALS -JAVA 7 FEATURE

Since Java 7, you can use underscores in the numeric literals.

Example:

// declaring a float value

float acc_balance = 5_000L;

Here, the value of the variable is 5000.0

 
Underscores in numeric literals are mainly used to separate the
significant parts of number.


For instance, lets consider 10-digit mobile number in india.


In a 10-digit mobile number, we have two significant parts:

. First four numbers XXXX represents the network operator.

. the last numbers NNNNNN represents the subscriber number.

XXXX-NNNNN

Example:

int phoneNumber = 9849_751031;

This new feature is intended to improve the code readability.


Some examples where you need this feature- to represent:

 . Debit Card Number
 . Credit Card Number
 . Social Security Number


This feature is only a developer convenience.

Note: Compiler will ignore underscores in number literals.  

Example:

 public class Java7Literals {

    public static void main(String args[]){

        long debitCard = 5555_3333_7777_9999L;

        System.out.println("debit card number: "+ debitCard);
      
        }

   }


output:

 debit card number: 5555333377779999

 Here compiler ignored the underscores.

As I said it is a developer convenience.


Some example declarations:

long ssNumber = 999_89_9999L;

printed as: 999899999

float pi = 3.14_15F;

printed as: 3.1415


Rules:
---------

places where not to place the underscores in numeric literals.


. At the beginning and at the end of the numbers


ILLEGAL

 long x3 = _77L;

int x5 = 55_;


. Adjacent to decimal point in a floating point literal

ILLEGAL

float pi =  3._14_15F;


LEGAL

float pi = 3.14_15F;


 .Prior to D or L or F suffix

ILLEGAL

float pi  = 3.14_5_F;

.In positions where strings of digits is exepcted

ILLEGAL

int x5 =  0_x52

// cannot put underscore in the 0x radix prefix

int x6 = 0x_52

//cannot put the underscore at the beginning of the number


LEGAL


int x7  = 0x5_2;


Note: 

For illegal usage of the underscores as described above may yield an error

error: illegal underscore.

This feature can be applied to primitive data types in any supported 
base - octal, hexadecimal, binary  or decimal. 


the underscores in hexadecimal and binary are used in identifying the
parts of commands

Example:

int commandInHex = 0xE_25D5_8C_7;
int commandInBinary = 0b1110_0011111111010101_10001100_0111;


  Hope this is helpful

 If you like this, please share.

No comments:

Post a Comment