Integer.parseInt and NumberFormatException on Android

I ran the following code in my android application

Integer.parseInt("+91"); 

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

NumberFormatException: Invalid Int: "+91"

How does the Android version make this difference?

+43
java android
May 6 '15 at 8:38
source share
4 answers

Explicit + support has been added to this commit :

 Support explicit + in Byte, Short, Integer, Long. Bug: 5239391 Change-Id: I2b25228815d70d570d537db0ed9b5b759f25b5a3 

which has been enabled since android-5.0.0_r1 . If you checked out the Git repository, you can check with:

 git tag --contains 6b40837ee3a023bba698c38fd6d6e46ae0065a55 

which gives you

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

Although the documentation may give an idea of ​​why the change was made (to achieve Java 7 behavior, as other answers indicate), analyzing the source code history gives the most accurate answer to the behavior change, since the documentation does not necessarily correspond to the implementation.

+45
May 6 '15 at 8:48
source share
— -

This behavior is actually part of Java 7, and docs :

Parses a string argument as an integer with decimal precision. Characters in the string must be decimal numbers, except that the first character can be ASCII minus sign '-' ('\ u002D') to indicate a negative value or ASCII sign plus '+' ('\ u002B') to indicate positive value.

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

The Android SDK 21+ has JDK7 dependencies, which seems to be the reason why you experience this behavior.

+23
May 6 '15 at 8:45
source share

It works after Java 7.

Android 5 introduces a new parseInt feature like Java 7 version - Martin Nordolts answers exactly the question about version

So this means that your Lollipop uses the new Java 7 based sdk, which also has a parseInt method with part of the sign processing.

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




Difference between parseInt implementations: Java 6 parseInt documentation vs Java 7 parseInt documentation

+10
May 6 '15 at 8:43
source share

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

Android version 19 (KitKat) supports Java 7, so you won't get this error. I recommend not using + , because you only need a sign if you have a negative integer.

+5
May 6 '15 at 8:56
source share



All Articles