简体   繁体   中英

Integer.parseInt and NumberFormatException on Android

I ran the following code in my Android app

Integer.parseInt("+91");

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?

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

android-5.0.0_r1
android-5.0.0_r2
android-5.0.0_r3
...

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.

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 '-' ('\-') to indicate a negative value or an ASCII plus sign '+' ('\+') 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM