How to Convert Java String to Int

By | 2017-05-01T06:55:06+05:30 May 1st, 2016|java|0 Comments

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment