stranger
stranger

Reputation: 143

parseInt throws error

I have this small piece of code in java which throws the following error when the code is run

Exception in thread "main" java.lang.NumberFormatException: For input string: "10000000000" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:495) at java.lang.Integer.parseInt(Integer.java:527) at hello.main(hello.java:6)

public class hello {
    public static void main(String args[])
    {
        int x = 1024;
        String h = Integer.toString(x, 2);
        int xx = 9*(Integer.parseInt(h));
        System.out.println(xx);
    }
}

I suspect that this problem is related to the size of the values/parseInt. Can you please explain the reason for this error to me in detail.

Upvotes: 1

Views: 2181

Answers (3)

Moni
Moni

Reputation: 433

You are getting java.lang.NumberFormatException: For input string: "10000000000" because it exceed the range of int.

integer is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647. long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value, range is from –9,223,372,036,854,775,808 to 9 ,223,372,036,854,775,807. This makes it useful when big, whole numbers are needed.

Try this line of code-

long xx = 9*(Long.parseLong(h));

Upvotes: 3

ToxicPineapple
ToxicPineapple

Reputation: 88

You are receiving this error because you are trying to parse a value too large for the Integer type. Try using Long instead.

Upvotes: 2

PsyCode
PsyCode

Reputation: 664

This is because this surpasses the maximum value for an integer of 2,147,483,647

Upvotes: 4

Related Questions