Reputation: 1219
I am aware of the fact that this format long val = 1_000_000L;
is valid in java, but what I found non constitent is the behaviour of the Long#parseLong
method that does not parse this format if it is passed as a String
, I tried the below code and I always get the exception:
String h = "1_000_000L";
long val = 1_000_000L;
System.out.printf("this a valid format : %d\n", val);
try {
Long m = Long.parseLong(h);
System.out.println(m);
} catch (NumberFormatException e) {
System.out.printf("cannot parse this number : %s\n", h);
}
NB. I am building something like a personal java compiler and I want that it works without getting rid of the underscore format.
Upvotes: 4
Views: 1427
Reputation: 178313
There never was a requirement that numeric literal that you can type in source code would work the same way as numbers parsed from a String
.
Here is the Javadocs of Long.parseLong
:
The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' (\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
So not only are underscores not allowed, but the L
suffix also. It's not meant to parse numbers of the format from source code.
The underscores in numeric literals were introduced in Java 7, but only to improve readability of source code, not programmatic parsing of strings.
In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
These features are entirely separate and were never meant to be consistent with each other.
The NumberFormatException
you got is expected and it is working correctly.
Upvotes: 1