How to parse numbers in Java (Convert text into a number)

Friday, April 25, 2008

This article will discuss how to convert text and change it into a number. Having the ability to parse text into a number comes useful when accepting numerical input from the user. Some examples include taking a command line argument which is passed as a String and obtaining an int, taking an input from a TextField and obtaining an int.

We will discuss the Integer.parseInt(String) method and their variants.

Using Integer.parseInt(String)

The Integer.parseInt(String) method can accept a String object and return an int value. The parseInt(String) method is a static method of the Integer class, so it is not necessary to instantiate an Integer object to call the method.

The following is an example of using the Integer.parseInt(String) method to convert a String to an int:

/**
 * ParseInt demonstrates the use of String parsing methods to retrieve
 * a number from text.
 * @author coobird
 */
public class ParseInt {
  public static void main(String[] args) {
    // String that we want to make an integer
    String str = "123";

    // Parses the String to obtain an int called number.
    int number = Integer.parseInt(str);
    
    // Just to prove we have an int. Increment it.
    number++;
    
    // Displays the incremented int to the console.
    // It should print out "124"
    System.out.println(number);
  }
} 

In the example above, the String object containing the text 123 is parsed to obtain an int called number. The number variable is incremented and displayed to the console. The result should be 123 + 1 which is 124. Running the above program, we obtain:

124

As expected, 124 is the result produced by the program.

Another parseInt method is the overloaded Integer.parseInt(String, int) method, which specifies the radix of the number being converted. This comes useful when trying to parse a number that is not base 10, such as binary, octal, hexadecimal to name a few. The following is an example parses a String containing FF, hexadecimal for 255, which is parsed as a hexadecimal (base 16):

/**
 * ParseInt2 demonstrates the use of String parsing methods to retrieve
 * a number from text containing a hexadecimal.
 * @author coobird
 */
public class ParseInt2 {
  public static void main(String[] args) {
    // String that we want to make an integer
    // FF is hexadecimal for 255.
    String str = "FF";

    // Parses the String to obtain an int called number, specifying
    // the radix as 16 (hexadecimal)
    int number = Integer.parseInt(str, 16);
    
    // Just to prove we have an int. Increment it.
    number++;
    
    // Displays the incremented int to the console.
    // It should print out "256"
    System.out.println(number);
  }
}

As with the first example, a String is parsed and an int is returned. This time, the String is handled as a hexadecimal, so the line Integer.parseInt("FF", 16)returns 255, which is incremented to 256. When running the program, the output is:

256

As expected, the result is 256.

This second example may come handy when dealing with memory addresses, byte values, or color codes in HTML which are often expressed in hexadecimal.

So far, we’ve seen examples where the text contains a number in String representation. The next section will handle cases when text that can’t be parsed is passed into the parseInt method.

Error Handling

When accepting an String as an input that we want to convert to a number, we can’t assume that the String will always contain a number that can be parsed. For example, the String may contain words and letters.

What would happen if we try to parse a String containing the text one? We’ll try to run the following program to find out:


/**
 * ParseInt3 demonstrates what happens when we try to parse the
 * text "one" to a number.
 * @author coobird
 */
public class ParseInt3 {
  public static void main(String[] args) {
    // String that we want to make an integer
    // "one" is obviously not a number (at least in base 10)
    String str = "one";

    // Parses the String to obtain an int called number.
    // What happens?
    int number = Integer.parseInt(str);
    
    // Hint: we never reach this line.
    System.out.println(number);
  }
}

Running the above program, the following is what is displayed in the console:

Exception in thread "main" java.lang.NumberFormatException: For input string: "one"
  at java.lang.NumberFormatException.forInputString(Unknown Source)
  at java.lang.Integer.parseInt(Unknown Source)
  at java.lang.Integer.parseInt(Unknown Source)
  at ParseInt3.main(ParseInt3.java:16)</pre>

The program generated a NumberFormatException when attempting to run the Integer.parseInt(str) line. We can see that the exception was thrown because the input string was “one”, according to the exception message. There is a list of situations where a NumberFormatException is thrown by the parseInt(String) and parseInt(String, int) methods on the Integer.parseInt(String, int) javadoc.

As an exception is thrown, the program crashes at that point. To prevent this from happening, the exception must be caught. The following shows the previous program with exception handling by using try-catch:

/**
 * ParseInt4 demonstrates what happens when we try to parse the
 * text "one" to a number. This version adds a try-catch block for
 * exception handling
 * @author coobird
 */
public class ParseInt4 {
  public static void main(String[] args) {
    // String that we want to make an integer
    // "one" is obviously not a number (at least in base 10)
    String str = "one";

    // Initialize the variable we want to store to.
    int number = 0;
    
    // Parses the String to obtain an int called number.
    // What happens?
    try {
      number = Integer.parseInt(str);
    } catch (NumberFormatException nfe) {
      System.out.println("Could not parse: " + str);
    }
    
    // Print out what's in the variable.
    System.out.println(number);
  }
}

The output from running the above example was:

Could not parse: one
0

This time, rather than the program crashing at runtime like the previous example, the NumberFormatException was caught in the catch block. This allows for exception handling where we can print out a message to inform the user that the input was not valid. As evidenced by the second line of 0, we can see that the final line, System.out.println(number);, was executed, so the program didn’t crash like the last example.

Other parse Methods

There are other parse methods in the Java API aside from Integer.parseInt. The following is a quick list:

The above methods are static method like the Integer.parseInt(String) method, so they work in a similar fashion, where the input is a String and the output is a primitive type of the wrapper class of the type (e.g. Boolean.parseBoolean(String) returns a primitive boolean type.