There are 2 ways by which you can convert String to Integer. Both methods are defined in Integer class. They are:
- Using Integer.parseInt(String)
- Using Integer.valueOf(String)
Let's see an example of both:
Conversion Using Integer.parseInt(String):
public class ConvertStrToInt {
public static void main(String[] args) {
String number = "99";
try{
// String to integer
int result = Integer.parseInt(number);
// 99
System.out.println(result);
} catch (NumberFormatException e) {
//handle exception as you want
System.err.println("Invalid format : " + number);
}
}
}
Conversion Using Integer.valueOf(String):
public class ConvertStrToInt {
public static void main(String[] args) {
String number = "99";
try{
// String to integer
Integer result = Integer.valueOf(number);
// 99
System.out.println(result);
}catch (NumberFormatException e) {
//handle exception as you want
System.err.println("Invalid format : " + number);
}
}
}
As you can see in both of the Examples above, converts a String to an Integer, so the only difference between the two is that the Integer.parseInt(String) method converts a String to primitive type int; whereas the Integer.valueOf(String) method convert a String to a Integer object.
Also, Always add above code in a try-catch block like we have added, as it can throw a NumberFormatException for unparsable String.