Sunday, 22 December 2013

Underscores Between Digits in Numeric Literals

Underscores are permitted in numeric literals. You can place underscores where you feel required to increase readability; like between hundreds and thousands, thousands and lakhs etc.
This is used to group numbers in a bigger literal value (especially of long data type).
Note: Do not place underscore at the beginning or ending of the literal value.
public class Demo
{
  public static void main(String args[])
  {
    int flatCost = 48_87_653;

    float buildingCost = 6_47_812.25_67f;

    System.out.println("Flat cost Rs. " + flatCost);   
    System.out.println("Building cost Rs. " + buildingCost);   
   }
}


Note: But following does not work (cannot parse with underscores).
    String str ="12_34";
    int x = Integer.parseInt(str);
The above parsing raises NumberFormatException.


No comments:

Post a Comment