In this tutorials, I am going to show you how to convert Java String to int.
Convert Java String to Int :
We can convert Java String to int using Integer wrapper class.
Using String class : Integer.valueOf(String)
[box type=”shadow” align=”alignleft” class=”” width=”100%”]
String str = “1500”;
Integer.valueOf(str);
[/box]
Using Integer Wrapper : Integer.parseInt(String)
[box type=”shadow” align=”alignleft” class=”” width=”100%”]
String str = “100”;
Integer.parseInt(str);
[/box]
On the above two possibilities, we can convert the String to int in Java. But while converting, we should take care about exceptions; means the both methods will raise java.lang.NumberFormatException, only if the String can not be convertible to int.
[box type=”shadow” align=”alignleft” class=”” width=”100%”]
String str = “1500A”;
Integer.valueOf(str);
[/box]
On the above example str contains alphabet, it will not convertible to int, hence we can get NumberFormatException here like below.
[box type=”error” align=”alignleft” class=”” width=”100%”]
Exception in thread “main” java.lang.NumberFormatException: For input string: “1500A”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.valueOf(Integer.java:582)
[/box]
Happy Learning 🙂