Integer.parseInt()
Converts a string containing an integer to an int.
Available since: Java 1.0
Syntax
static int parseInt(String s)Parameters
| Parameter | Type | Description |
|---|---|---|
| s | String | A string of digits with an optional + or - sign. There is a version with a second argument, the radix. |
Return value
intThe number as an int.
Examples
Strings to numbers:
void main() {
int a = Integer.parseInt("42");
int b = Integer.parseInt("-7");
IO.println(a + b);
IO.println(Integer.parseInt("ff", 16));
}Output:
35
255An invalid string throws NumberFormatException:
void main() {
String[] inputs = {"15", " 15", "1.5", ""};
for (String s : inputs) {
try {
IO.println(Integer.parseInt(s));
} catch (NumberFormatException e) {
IO.println(e.getMessage());
}
}
}Output:
15
For input string: " 15"
For input string: "1.5"
For input string: ""Notes
Spaces are not allowed — remove them with strip() before parsing. Decimal strings are parsed by Double.parseDouble(), numbers above 2,147,483,647 by Long.parseLong().
See also
- Integer.valueOf() — Returns an Integer wrapper object for a string or an int.
- Double.parseDouble() — Converts a string with a decimal number to a double.
- Long.parseLong() — Converts a string with an integer to a long — for numbers that do not fit in an int.
- String.valueOf() — Converts a value of any type to a string.
- NumberFormatException — Thrown when a string cannot be converted to a number.
Related recipes
In the tutorial
- Type conversion — Automatic widening, explicit (int) casts, turning strings into numbers with Integer.parseInt and numbers into strings.