Reputation: 1967
The following code builds a StringBuilder, set its length to 11, and the go through each character of the string to replace it with "5". It gives NumberFormatException although the length is proper and the content too.
StringBuilder str = new StringBuilder();
str.setLength(11);
for(int i = 0; i < 11; i++){
System.out.println(str.toString());
str.replace(i, j, "5");
System.out.println(i + " " + j);
}
System.out.println(Integer.parseInt(str.toString()));
Upvotes: 2
Views: 305
Reputation: 290
According to Java Language specifications:
The width of int is 32 bits, hence the range of an int variable is -2147483648 to +2147483647. The long is of 64 bits with the range -9223372036854775808 to +9223372036854775807
Change to below line in your code:
System.out.println(Long.parseLong(stringBuilder.toString()));
Upvotes: 3
Reputation: 91
Possibly because your String with number is larger than the maximum length for Integers values. Try to parse to Long.
Upvotes: 6
Reputation: 2066
You know that an Integer has 2147483647 as max value? So 55555555555 will not work. Use Long or less then 10 digits.
Upvotes: 2