In this tutorial, you will learn how to convert a String to int in Java. If a String is made up of digits like 1,2,3 etc, any arithmetic operation cannot be performed on it until it gets converted into an integer value. In this tutorial we will see the following two ways to convert String to int:
- Using Integer.parseInt()
- Using Integer.valueOf()
1. Using Integer.parseInt()
The Integer.parseInt()
method converts a String
to a primitive int
. I have covered this method in detail here: Integer.parseInt()
Method
String number = "123";
int result = Integer.parseInt(number);
System.out.println(result); // Output: 123
2. Using Integer.valueOf()
The Integer.valueOf()
method converts a String
to an Integer
object, which can then be unboxed to a primitive int
.
String number = "123";
int result = Integer.valueOf(number);
System.out.println(result); // Output: 123
3. Handling Exceptions
Both of these methods throw NumberFormatException
, if the string cannot be parsed as an int. It is always a good practice to place the conversion code inside try block and handle this exception in catch block to avoid unintentional termination of the program.
String number = "123abc"; // This will cause an exception
try {
int result = Integer.parseInt(number);
System.out.println(result);
} catch (NumberFormatException e) {
System.out.println("This value cannot be parsed as an integer");
}
String to int Conversion Example
Let’s write a complete program for string to int conversion using both the methods that we discussed above. We are also handling exception, if in case the string cannot be parsed as an integer.
public class StringToIntExample {
public static void main(String[] args) {
String validNumber = "123";
String invalidNumber = "123a";
// Using Integer.parseInt() method
try {
int result = Integer.parseInt(validNumber);
System.out.println("Using Integer.parseInt(): " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + validNumber);
}
// Using Integer.valueOf() method
try {
int result = Integer.valueOf(validNumber);
System.out.println("Using Integer.valueOf(): " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + validNumber);
}
// Handling NumberFormatException for invalid input
try {
int result = Integer.parseInt(invalidNumber);
System.out.println("Using Integer.parseInt(): " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + invalidNumber);
}
}
}
Output:
Using Integer.parseInt(): 123
Using Integer.valueOf(): 123
Invalid number format: 123a
Leave a Reply