Java Programming Tutorials

Java programming tutorials with many code examples!

Java String to int

In Java String to int conversion can be done in a few different ways. In this post we’ll show them and describe differences.

String to int

To create primitive int from String you can use Integer.parseInt(String):

int x = Integer.parseInt("42");
System.out.println("int is: " + x);

The above code produces the following output:

int is: 42

NumberFormatException when conversion fails

When Java cannot convert given String to int then NumberFormatException is thrown:

try {
    Integer.parseInt("aoeu");
} catch (NumberFormatException e) {
    e.printStackTrace();
}

The above code prints:

java.lang.NumberFormatException: For input string: "aoeu"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:580)
        at java.lang.Integer.parseInt(Integer.java:615)
        at com.farenda.java.lang.StringToInt.numberFormatException(StringToInt.java:18)
        at com.farenda.java.lang.StringToInt.main(StringToInt.java:7)

String to Integer

If you would like to convert String to Integer then there is Integer.valueOf(String) method exactly for that purpose:

Integer x = Integer.valueOf("42");
System.out.println("Integer is: " + x);

The code prints:

Integer is: 42

Note: It’s exactly like creating an Integer from result of Integer.parseInt(String).

NumberFormatException when String to Integer fails

Also here, when String to Integer conversion fails, the NumberFormatException is thrown:

try {
    Integer.valueOf("xyz");
} catch (NumberFormatException e) {
    e.printStackTrace();
}

Prints the following:

java.lang.NumberFormatException: For input string: "xyz"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:580)
        at java.lang.Integer.valueOf(Integer.java:766)

Integer from String in other base

Integer.decode(String) can be used to create Integer from octal, decimal, or hex String. Of course, this method may throw NumberFormatException as any other method that tries to create something from a String.

Octal String to Integer

System.out.println("From oct: " + Integer.decode("052"));

Prints:

From oct: 42

Decimal String to Integer

System.out.println("From dec: " + Integer.decode("42"));

Prints:

From dec: 42

Hex String to Integer

System.out.println("From hex: " + Integer.decode("0x2a"));

Prints:

From hex: 42
Share with the World!