Appearance
How do I convert a String to an int in Java?
To convert a String to an int in Java, you can use the parseInt() method of the Integer class. Here's an example:
java
String str = "123";
int num = Integer.parseInt(str);The parseInt() method takes a String as an argument and returns the corresponding int value. It fully supports negative integers (e.g., "-456"). If the String does not contain a valid integer, it will throw a NumberFormatException. To handle this safely, wrap the call in a try-catch block:
java
String str = "abc";
try {
int num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Invalid number format");
}You can also use the valueOf() method of the Integer class to achieve the same result:
java
String str = "123";
int num = Integer.valueOf(str);By default, both methods parse decimal numbers. To parse hexadecimal, octal, or binary strings, you must specify a radix (e.g., Integer.parseInt(str, 16)) or use Integer.decode(str).