Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Integer.parseInt()

Converts a string containing an integer to an int.

Available since: Java 1.0

Syntax

static int parseInt(String s)

Parameters

ParameterTypeDescription
sStringA 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
255

An 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

Related recipes

In the tutorial

  • Type conversion — Automatic widening, explicit (int) casts, turning strings into numbers with Integer.parseInt and numbers into strings.

Thanks for reading!

Donate to the site — we work hard for you.