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);
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);
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.");
}
Top comments (0)