Did you try parsing a number residing in a String and an exception occured when that number was 8 or 9?

Parsing String numbers

When parsing numbers residing in Strings one should pay attention to the parsing method.

There are several parsing methods in the Integer Class, and not all of them parse the numbers in a Decimal (Base 10) order.

For example if you'll try running the following line of code - an exception will be thrown: Integer i = Integer.decode("09");

The exception will be thrown due to the simple fact that there is no numeric character 09 when you use an Octalic counting base (Which is the decode method's default).

Try using a different method for a Decimal based number.

So, in order to correct our specific example we should use: Integer i = Integer.parseInt("09");

Comments

Lurker said…
Actually, the reason why the exception is thrown in this case is that the string begins with a "0". In Java, a numeric constant beginning with "0" is assumed to be an octal number (just as a numeric constant beginning with "0x" is assumed to be a hexadecimal number). This syntax is inherited from C/C++. So once the parser routine sees the "0", it enters octal parsing mode. When it then encounters a "9" (or an "8"), it throws an exception, because there is no such digit in octal.

If you strip off the zero, and do it this way:

Integer i = Integer.decode ("9");

then it will work just fine.

Popular posts from this blog

Profiling Java @ 2019

Shared/Pro/Managed Hosting for your site - which to choose ? (NO AFFILIATE LINKS!)

ZVR converter