Java – How to resolve the NumberFormatException in Java when trying to convert very large numbers from a String

How to resolve the NumberFormatException in Java when trying to convert very large numbers from a String… here is a solution to the problem.

How to resolve the NumberFormatException in Java when trying to convert very large numbers from a String

I’m trying to convert each character of a string to its ASCII value and concatenate those values as int.

Example:

Input: “Z8IG4”

Output: 9056737152.

What I’ve done so far is:

String m = "Z8IG4";
String nm = "";

for(int i=0; i<m.length(); i++){
  char c = m.charAt(i);
  int cm = (int) c;
  nm+=Integer.toString(cm);
}

int foo = Integer.parseInt(nm);
System.out.println(foo);

This doesn’t work, I don’t know what I’m doing wrong here.

Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "9056737152"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.parseInt(Integer.java:615)
at HelloWorld.main(HelloWorld.java:22)

Solution

This is because the maximum value supported by int is 2147483647 and your value is out of range.

You can use Integer.MAX_VALUE to find the maximum value

To do this you can use BigInteger f = new BigInteger(nm);

Related Problems and Solutions