Search code examples
javaruntime-errornumberformatexception

Getting a strange NumberFormatException while trying to parse a string to an int


I am getting the following exception - Kindly advise

java.lang.NumberFormatException: For input string: "2"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)

There seem to be no whitespaces as you can see "2". I just split a string and get "2" as one of the elements of the split array then I get this while trying to parse it into an int

Kindly advise


Solution

  • Can you please post your code. beacuse if exception is

    java.lang.NumberFormatException: For input string: "2"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:492)
    

    this means your String say s is 2 not "2" and for "2" you cann't use

    Integer myInt = Integer.parseInt(" \"2\" ");
    

    This will any way give you Number format exception. Because you cann't part string to it, only number is parse using Integer.parseIn() and "2" is String.