How do I convert a String to an int in Java?

15 Answers

For example, here are two ways:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

convert string to integer python

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

Do it manually:

public static int strToInt( String str ){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    //Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;

    //Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).

    if (isNeg)
        num = -num;
    return num;

An alternate solution is to use Apache Commons' NumberUtils:

int num = NumberUtils.toInt("1234");

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.

Apache NumberUtils API Version 3.4

Whenever there is the slightest possibility that the given String does not contain an Integer, you have to handle this special case. Sadly, the standard Java methods Integer::parseInt and Integer::valueOf throw a NumberFormatException to signal this special case. Thus, you have to use exceptions for flow control, which is generally considered bad coding style.

In my opinion, this special case should be handled by returning an Optional<Integer>. Since Java does not offer such a method, I use the following wrapper:

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();


// prints 1234
// prints -1

While this is still using exceptions for flow control internally, the usage code becomes very clean.

We can use the parseInt(String str) method of the Integer wrapper class for converting a String value to an integer value.

For example:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

The Integer class also provides the valueOf(String str) method:

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

We can also use toInt(String strValue) of NumberUtils Utility Class for the conversion:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);

Use Integer.parseInt(yourString)

Remember following things:

Integer.parseInt("1"); // ok

Integer.parseInt("-1"); // ok

Integer.parseInt("+1"); // ok

Integer.parseInt(" 1"); // Exception (blank space)

Integer.parseInt("2147483648"); // Exception (Integer is limited to a maximum value of 2,147,483,647)

Integer.parseInt("1.1"); // Exception (. or , or whatever is not allowed)

Integer.parseInt(""); // Exception (not 0 or something)

There is only one type of exception: NumberFormatException

Just for fun: You can use Java 8's Optional for converting a String into an Integer:

String str = "123";
Integer value = Optional.of(str).map(Integer::valueOf).get();
// Will return the integer value of the specified string, or it
// will throw an NPE when str is null.

value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
// Will do the same as the code above, except it will return -1
// when srt is null, instead of throwing an NPE.

Here we just combine Integer.valueOf and Optinal. Probably there might be situations when this is useful - for example when you want to avoid null checks. Pre Java 8 code will look like this:

Integer value = (str == null) ? -1 : Integer.parseInt(str);

You can also begin by removing all non-numerical characters and then parsing the int:

string mystr = mystr.replaceAll( "[^\\d]", "" );
int number= Integer.parseInt(mystr);

But be warned that this only works for non-negative numbers.

You can use new Scanner("1244").nextInt(). Or ask if even an int exists: new Scanner("1244").hasNextInt()

You can use this code also, with some precautions.

  • Option #1: Handle the exception explicitly, for example, showing a message dialog and then stop the execution of the current workflow. For example:

            String stringValue = "1234";
            // From String to Integer
            int integerValue = Integer.valueOf(stringValue);
            // Or
            int integerValue = Integer.ParseInt(stringValue);
            // Now from integer to back into string
            stringValue = String.valueOf(integerValue);
    catch (NumberFormatException ex) {
        //JOptionPane.showMessageDialog(frame, "Invalid input string!");
        System.out.println("Invalid input string!");
  • Option #2: Reset the affected variable if the execution flow can continue in case of an exception. For example, with some modifications in the catch block

    catch (NumberFormatException ex) {
        integerValue = 0;

Using a string constant for comparison or any sort of computing is always a good idea, because a constant never returns a null value.

Simply you can try this:

  • Use Integer.parseInt(your_string); to convert a String to int
  • Use Double.parseDouble(your_string); to convert a String to double


String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55

int foo=Integer.parseInt("1234");

Make sure there is no non-numeric data in the string.

I am a little bit surprised that nobody didn't mention Integer constructor that takes String as a parameter.
So, here is:

String myString = "1234";
int i1 = new Integer(myString);

Java 8 - Integer(String).

Of course, the constructor will return type Integer, and unboxing operation converts value to int.

It's important to mention
This constructor calls parseInt method.

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);

Use Integer.parseInt() and put it inside a try...catch block to handle any errors just in case a non-numeric character is entered, for example,

private void ConvertToInt(){
    String string = txtString.getText();
        int integerValue=Integer.parseInt(string);
    catch(Exception e){
         "Error converting string to integer\n" + e.toString,

By the way, be aware that if the string is null, the call:

int i = Integer.parseInt(null);

throws NumberFormatException, not NullPointerException.