Jason Pather
Jason Pather

Reputation: 1157

Converting String to int in Java and getting a NumberFormatException, can't figure out why

ipString is a String representation of an IP address with spaces instead of dots.

String[] ipArray = ipString.split(" ");
String ip = "";
for (String part : ipArray){
    if (part != null){
        ip += part;
    }
}
ip = ip.trim();
int ipInt = Integer.parseInt(ip); // Exception is thrown here.

Exception in thread "main" java.lang.NumberFormatException: For input string: "6622015176". Could someone explain why this exception is being thrown?

Upvotes: 0

Views: 562

Answers (3)

Nagaraj
Nagaraj

Reputation: 145

public class test {
    public static void main(String args[]) {
        String ipString="662 20 15 176";
        String[] ipArray = ipString.split(" ");
        String ip = "";
        for (String part : ipArray){
            if (part != null){
                ip += part;
            }
        }
        ip = ip.trim();        
        Long ipInt = Long.parseLong(ip);
        System.out.println(""+ipInt);
    }
}

Upvotes: 0

Tushar Paliwal
Tushar Paliwal

Reputation: 301

6,622,015,176 This number is out of range of int.You should use long instead of int which will provide you a large range.

Upvotes: 0

kosa
kosa

Reputation: 66637

int is primitive data type and it's range is : -2,147,483,648 to 2,147,483,647

6,622,015,176 is out of int range.

Upvotes: 4

Related Questions