Convert String to Integer in Java

In this article, you will learn how to convert a string to an integer In Java. A string should be parsable in order for the operation to succeed. Otherwise, the program will throw a NumberFormatException exception.

More like this:

Convert String to an integer using Java

In Java, we can simply use the function Integer.valueOf to convert a string into an integer.

For example:

Integer.valueOf("33");

Will return an integer value of 33.

Examples of converting string to an integer using Java

public class Main
{
  public static void main (String[]args)
  {
    Integer.valueOf ("10");	// returns 10
    
    Integer.valueOf ("+10");	// returns 10
    
    Integer.valueOf ("-10");	// returns -10
 
    Integer.valueOf ("1 0");// NumberFormatException, cannot caintain space
 
    Integer.valueOf ("9087984321");// NumberFormatException, exeeds max integer values of  2,147,483,647  bytes
    
    Integer.valueOf ("1 @ 1");// NumberFormatException, symbols are not allowed

    Integer.valueOf ("");// NumberFormatException, empty string
    
    Integer.valueOf (null);// NumberFormatException, null value

  }
}

NumberFormatException Exception in Java

as mentioned before,  if a string is not parsable, the program will throw the NumberFormatException exception.

For Example:

Integer.valueOf ("1 0"); // Space is not allowed

This code will throw the exception below since space is not allowed character in a number.

Exception in thread "main" java.lang.NumberFormatException: For input string: "1 0"
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.base/java.lang.Integer.parseInt(Integer.java:652)
        at java.base/java.lang.Integer.valueOf(Integer.java:983)
        at Main.main(Main.java:14)

Example of NumberFormatException Exception in Java

Use the Try Catch block to avoid a termination of the program when an exception occurs. The example below demonstrate how to handle the NumberFormatException exception in your Java program.

public class Main
{
  public static void main (String[]args)
  {

    String stringNumber = " 10"; // Contains space.
    Integer result;
    try
    {
       result = Integer.valueOf (stringNumber);
      System.out.println (result);
    }
    catch (NumberFormatException e)
    {
 
      System.err.println ("Invalid number format.");
    }

  }
}

Output

Invalid number format.

Happy coding!