Wednesday, February 10, 2016

That Underscores Are Valid In Java Numeric Values

No comments

Wasn't That Obvious

While taking an exam, I encountered a question whose answer seems to be pretty obvious. Even at first glance, I said duh this is so obvious! Well it turns out when you're taking an exam and something seems so obvious, you have to doubt yourself.
 Q:  Which of the following lines of code compile? (Choose all that apply)
     A. int i1 = 1_234;
     B. double d1 = 1_234_.0;
     C. double d2 = 1_234._0;
     D. double d3 = 1_234.0_;
     E. double d4 = 1_234.0;
     F. None of the above.

Did you get A & E ? I didn't. Today me and my team mates are preparing for our OCA 8 certification. We decided to take an assessment exam and I encountered this question. I thought "Isn't that obvious" and I answered F. I have never been so wrong. 

So Underscores Are Valid Numeric Literals

Yes they are, starting from Java 7. You can even use it in Hex, Octal and Binary literals. There are a few rules when using it though:
  • Any number of underscore characters (_) can appear anywhere between digits in a numerical literal
  • Underscores cannot be put adjacent to a decimal point
  • Numeric literals cannot start with an underscore 
  • Numeric literals cannot end with an underscore 
  • Underscores cannot be put prior to an L suffix
  • Underscores cannot be put in the 0x radix prefix
Visit the Oracle Documentation for more info.

No comments :

Post a Comment