How to convert a String to an int and back
Short answer
Integer.parseInt() turns a string into an int, and String.valueOf() turns a number into a string:
void main() {
int number = Integer.parseInt("42");
String text = String.valueOf(number);
IO.println(number + 1);
IO.println(text + 1);
}Output:
43
421Other number types
Every number type has its own parseXxx() method:
void main() {
long big = Long.parseLong("9000000000");
double price = Double.parseDouble("19.99");
IO.println(big);
IO.println(price * 2);
}Output:
9000000000
39.98A wrapper object instead of a primitive
Integer.valueOf() returns an Integer object — you need one, for example, to put a number into a List<Integer>:
void main() {
List<Integer> numbers = new ArrayList<>();
numbers.add(Integer.valueOf("7"));
numbers.add(Integer.valueOf("8"));
IO.println(numbers);
}Output:
[7, 8]A number to a string
Besides String.valueOf(), you can use Integer.toString() or concatenation with an empty string. For formatting use String.format():
void main() {
int count = 5;
String a = Integer.toString(count);
String b = "" + count;
String c = String.format("%03d", count);
IO.println(a + " " + b + " " + c);
}Output:
5 5 005Bad input
If the string is not a number, parseInt() throws a NumberFormatException. Catch it to fall back to a default value:
int toInt(String text, int fallback) {
try {
return Integer.parseInt(text.strip());
} catch (NumberFormatException e) {
return fallback;
}
}
void main() {
IO.println(toInt(" 15 ", 0));
IO.println(toInt("abc", 0));
}Output:
15
0Common mistake
parseInt() does not strip spaces and does not accept a fractional part — such strings cause an exception:
void main() {
int value = Integer.parseInt("3.5");
IO.println(value);
}Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "3.5"Use Double.parseDouble() for decimal numbers and remove spaces with strip().
Functions used in this recipe
- Integer.parseInt() — Converts a string containing an integer to an int.
- Integer.valueOf() — Returns an Integer wrapper object for a string or an int.
- String.valueOf() — Converts a value of any type to a string.
- Double.parseDouble() — Converts a string with a decimal number to a double.