Search code examples
javaexceptionnumberformatexception

NumberFormatException while converting a string to an integer value in java


When I'm trying to parse the input1 string to an integer value it's rising a NumberFormatException.I've tried replacing the spaces if any in the string but it didn't work for me.

int number = 0;
 String input1 = "12345354987"; 
 try{
   ip = Integer.parseInt(input1);

  }catch(NumberFormatException e){
        System.out.println("not a number");
    }

Solution

  • Its because the Number in String is out of Integer range, If you really need this than use BigInteger for large values like this :

     String input1 = "12345354"; 
             BigInteger ib =new BigInteger(input1);
             System.out.println(ib);
    

    or For small values that can fit in Long range you can use :

    String input1 = "1234535455"; 
               Long ip = Long.parseLong(input1);
               System.out.println(ip);