Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
421

Other 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.98

A 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 005

Bad 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
0

Common 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

Thanks for reading!

Donate to the site — we work hard for you.