F:\Underscores in Numeric Literals>javac _.java
_.java:6: error: illegal underscore
byte me = 0b_111101;// not valid
_.java:7: error: illegal underscore
int x6 = 0x_52;//then how it is valid ?
If you want to know the exact rules for this, then it's time to look in the Java Language Specification. Paragraph 3.10.1 specifies the notation for integer literals. Read this paragraph carefully; it explains exactly where underscores are allowed and not allowed for decimal, hexadecimal, octal and binary integer literals.
If you read it carefully you'll see that 0x_52 is not valid, and 0_52 is valid. If you want to know why it was defined in this way, then that's a question you should ask the person who defined those rules. The specification doesn't really explain why the designer chose to make 0x_52 invalid. It's just how it is.
While the main conversation is going on, let me tackle the side question.... Let's say you are working on a 10 gigE network, and need to confirim how close you are using the 10 million bits of bandwidth. So, you have a constant in your application....
public int rate = 10000000;
Is this constant really readable? Or do you wind up going back, ever so often, to confirm that it has the correct number of zeros? Now....
saloni jhanwar wrote:Thank you Jesper de Jong.I found something in JLS.
Which would presumably be this excerpt from paragraph 3.10.1. Integer Literals :
In a hexadecimal or binary literal, the integer is only denoted by the digits after the 0x or 0b characters and before any type suffix. Therefore, underscores may not appear immediately after 0x or 0b, or after the last digit in the numeral.
In a decimal or octal literal, the integer is denoted by all the digits in the literal before any type suffix. Therefore, underscores may not appear before the first digit or after the last digit in the numeral. Underscores may appear after the initial 0 in an octal numeral (since 0 is a digit that denotes part of the integer) and after the initial non-zero digit in a non-zero decimal literal.
Sure, in general. But "there's nothing left to explain" seems to preclude the possibility of further discussion beyond what's in the JLS. Dennis had a helpful point to make that was not covered in the JLS, so he made it.
Yes, of course! I don't think I ever implied otherwise? And if I did I sure didn't intend to.
Joined: Mar 12, 2011
Jelle Klap wrote:It actually pretty much is.
Underscores are allowed as separators between digits that denote the integer
Separators, in the context of numbers, are usually intended for the sole purpose of improving readability, no?
Cool, thanks, I totally missed that line. This is far from my first encounter with the JLS, but I frequently have difficulty drawing useful information from it. I think, in general, the JLS is one of the less helpful sources to which we can direct beginning Java programmers. They probably can get more help from a clear, human-readable text.