Use Integer.parseInt
class MyConvertor {
public static void main(String[] args) {
String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123
}
}
Catch the exception if you want to handle the conversion error:
class MyConvertor {
public static void main(String[] args) {
String str = "abc";
try {
int num = Integer.parseInt(str);
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("Invalid integer format"); // Output: Invalid integer format
}
}
