java.lang.NumberFormatException: while parsing String to Integer in Java


In this Example we are going to understand the exceptions while parsing the string to int .

Error Message :
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
       at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
       at java.base/java.lang.Integer.parseInt(Integer.java:668)
       at java.base/java.lang.Integer.parseInt(Integer.java:776)
       at com.src.ArrayDititsSum.convertInt2Array(ArrayDititsSum.java:26)
       at com.src.ArrayDititsSum.main(ArrayDititsSum.java:12)

Error Description :

package com.src;

public class ArrayDititsSum {

       public static void main(String[] args) {
             
              convertArray(963);
       }
       public static void convertArray(int num)  {
           String str = Integer.toString(num);
           String temp;
           int temp1;
           int [] intArray = new int[str.length()];
           for(int i=0;i<=str.length();i++) {
               if (i!=str.length()) {
                   temp = str.substring(i, i+1);
               } else {
                   temp = str.substring(i);
               }
               temp1 =  Integer.parseInt(temp);   
               intArray[i] = temp1;
           }
                   }         

}
In the above example due to the yellow background color code we are getting the error of  red background color code.
While iterationthe iteration value starts from 0 and it will iterate more then the string length so the string value come as "" and the controller will go to else part and giving the NumberFormat Exception.


Solution:

We have simplified the code to avoid the exception. We should take care while giving the String input for parsing to Integer.

package com.src;

public class ArrayDititsSum {

       public static void main(String[] args) {
             
              convertArray(963);
       }
       public static void convertArray(int num)  {
           String str = Integer.toString(num);
           String temp;
           int temp1;
           int [] intArray = new int[str.length()];
           for(int i=0;i<str.length();i++) {
                   temp = str.substring(i, i+1);
               temp1 =  Integer.parseInt(temp);   
               intArray[i] = temp1;
              
           }
           System.out.println(intArray.length);             
       }

}
Output:
3

Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar