Integer.parseInt and NumberFormatException on Android

java android

2347 просмотра

4 ответа

I ran the following code in my Android app


In Android 5.0 (Lollipop), it did not throw any exception as +91 is an integer. But in Android 4.4.x (KitKat) and lower versions it throws:

NumberFormatException : Invalid Int : "+91"

How is the version of Android causing this difference?

Автор: Ashwin Источник Размещён: 12.11.2019 09:40

Ответы (4)

45 плюса


Support for explicit + was added in this commit:

Support explicit + in Byte, Short, Integer, Long.

Bug: 5239391
Change-Id: I2b25228815d70d570d537db0ed9b5b759f25b5a3

which has been included starting with android-5.0.0_r1. If you have fetched the Git repository, you can verify with:

git tag --contains 6b40837ee3a023bba698c38fd6d6e46ae0065a55

which gives you


Even though documentation can give insights into why the change was made (to achieve Java 7 behavior as other answers point out), analyzing the history of the source code gives the most accurate answer to when the behavior changed, since documentation does not necessarily match implementation.

Автор: Martin Nordholts Размещён: 06.05.2015 08:48

23 плюса

This behaviour is actually part of Java 7, as the docs state:

Parses the string argument as a signed decimal integer. 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.

However, in Java 6 only the - symbol was accepted.

The Android SDK 21+ has JDK7 dependencies, which is presumably why you are experiencing this behaviour.

Автор: Ed George Размещён: 06.05.2015 08:45

10 плюса

It works after Java 7.

Android 5 introduces the new parseInt feature like the Java 7 version - Martin Nordholts's answer points exactly the revision

So this means that your Lollipop uses a newer sdk based on Java 7 which has the parseInt method with the sign handling part too.

KitKat did introduce some java 7 features into Android sdk 19, but not the new parseInt. Lower versions use an earlier implementation of parseInt (Java 6's version) so they will obviously fail as well.

The difference between parseInt implementations : Java 6 parseInt documentation vs Java 7 parseInt documentation

Автор: Laurentiu L. Размещён: 06.05.2015 08:43

5 плюса

This is a Java-specific issue. As you see in the documentation, Java 6 allows - and Java 7 allows + or -.

With Android Version 19 (KitKat) Java 7 is supported, so you don't get this error. I recommend not to use +, because you only need a sign if you have a negative integer.

Автор: fabwu Размещён: 06.05.2015 08:56
Вопросы из категории :