Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Convert a String to an Integer in Java

Use Integer.parseInt() or Integer.valueOf(), and handle bad input without crashing.

How-To Guides2 min read10 screenshots

Why convert

User input, files, forms and API answers often arrive as text, even when they look like numbers. Java keeps text (String) and numbers (int) apart. Before you can add or compare numbers, you must parse the string.

Converting a string to an integer in Java

Integer.parseInt()

Integer.parseInt() returns a plain int. It is the most direct way.

public class StringToIntExample {
    public static void main(String[] args) {
        String input = "123";
        int number = Integer.parseInt(input);
        System.out.println("Converted number: " + number);
    }
}
The parseInt example
The output 123

The string must hold a valid whole number.

Integer.valueOf()

Integer.valueOf() returns an Integer object. Use it when you need an object, for example in a collection.

public class ValueOfExample {
    public static void main(String[] args) {
        String input = "789";
        Integer number = Integer.valueOf(input);
        System.out.println("Converted number (Integer object): " + number);
    }
}
The valueOf example
The Integer object output

Handle bad input

If the text is not a number, Java throws a NumberFormatException. Catch it:

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        String input = "abc"; // Invalid number

        try {
            int number = Integer.parseInt(input);
            System.out.println("Converted number: " + number);
        } catch (NumberFormatException e) {
            System.out.println("Error: Invalid number format.");
        }
    }
}
Handling NumberFormatException
The error message

parseInt() or valueOf()?

MethodReturnsUse it when
parseInt()intYou need a simple number and speed
valueOf()IntegerYou need an object

More examples

Binary, hex and other bases. Give the base as a second value:

public class BinaryToIntegerExample {
    public static void main(String[] args) {
        String binary = "1010"; // binary for 10
        int number = Integer.parseInt(binary, 2); // radix 2 = binary
        System.out.println("Binary to integer: " + number);
    }
}
Converting a binary string

Text with spaces. Remove the spaces with trim():

public class TrimAndConvertExample {
    public static void main(String[] args) {
        String input = "   321   "; // Has spaces
        int number = Integer.parseInt(input.trim());
        System.out.println("Converted number: " + number);
    }
}
Trimming the input
The output 321

Quick recap

  • parseInt() returns an int, valueOf() returns an Integer.
  • Catch NumberFormatException for text that is not a number.
  • Use trim() for spaces and a second argument for other bases.