How do I convert a String to an int in Java?
How to Convert a String to an int in Java
In Java, you can convert a String to an int using different methods, depending on the use case.
1. Using Integer.parseInt() (Most Common Method)
String str = "123";
int number = Integer.parseInt(str);
System.out.println(number); // Output: 123
- This is the most efficient way.
- Throws NumberFormatException if the string is not a valid number.
2. Using Integer.valueOf() (Returns an Integer Object)
String str = "456";
Integer number = Integer.valueOf(str);
System.out.println(number); // Output: 456
- Returns an Integer object instead of a primitive int.
- Useful when working with Integer objects instead of primitives.
3. Handling Errors with Try-Catch
String str = "abc";
try {
int number = Integer.parseInt(str);
System.out.println(number);
} catch (NumberFormatException e) {
System.out.println("Invalid number format!");
}
Helps prevent crashes if the input is not a valid number.
Which Method to Use?
- Use Integer.parseInt() for simple cases when you need an int.
- Use Integer.valueOf() when working with Integer objects.
- Always handle exceptions if input data is uncertain.