How Do I Convert A String to int in Java?

How Do I Convert A String to int in Java?

January 20, 2022

How Do I Convert A String to int in Java?

A Java String can be converted to an int in a number of ways. Let’s take a look at how to properly convert a String to an int in Java. The first example we will look at is the recommended way using best practices.

We declare and initialize a String below.

            
String theString = "123";
            
          

If we need to convert this string to an int, the best approach is to use one of the built-in Java Numbers Classes. You can reference the Java Number Classes for more information using the official Java Tutorials here. The Numbers Classes are essentially helper classes that allow you to “wrap” the primitive Java number data types (int, double, float, etc.) and manipulate them easier. There is a wrapper class for each primitive data type. The example we’re going to look at the Integer wrapper class which can be used with the primitive Java int data type. See How Do I Convert A String To A double in Java? for another example of Java Wrapper Classes with primitive data types. We are going to use the built in Java Integer Wrapper Class to do the conversion of our string to an int.


            
int myNumber = Integer.parseInt(theString);
            
          

In the code above we declared and created a new int named myNumber. We used the built in Java Wrapper Class Integer to parse our String created earlier and create a new int. The value of myNumber will be 123 after the execution of the above code. This is the recommended way to create an int data type from a string.

There is one more thing we are missing and that is to catch a possible exception. You are required to either surround the parseInt method with a try catch block, or you must declare a throws statement. The parseInt method can throw the NumberFormatException. The code below implements the try catch block.


            
int myNumber;
try {
    myNumber = Integer.parseInt(theString);
} catch (NumberFormatException e) {
    System.out.println("Failed to convert String to int");
}
            
          

The exception NumberFormatException will be thrown if your String cannot be converted to an int. This would typically happen if your String does not actually represent an int value.



Author Rob Lansing
2022 January 20th