DEV Community

Cover image for How do I convert a String to an int in Java ?
Rakesh KR
Rakesh KR

Posted on

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

To convert a String to an int in Java, you can use the Integer.parseInt() method. Here is an example:

String str = "123";
int num = Integer.parseInt(str);
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use the Integer.valueOf() method, which returns an Integer object rather than an int primitive. Here is an example:

String str = "123";
Integer num = Integer.valueOf(str);
Enter fullscreen mode Exit fullscreen mode

Keep in mind that both of these methods will throw a NumberFormatException if the string cannot be parsed as an integer. You can handle this exception by enclosing the call to Integer.parseInt() or Integer.valueOf() in a try-catch block.

try {
    String str = "123";
    int num = Integer.parseInt(str);
} catch (NumberFormatException e) {
    System.out.println("The string is not a valid integer.");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)