Newsletter |
How to Convert String to int in Java
Core Java » on Oct 15, 2016 { 1 Comment } By Sivateja
In Java we can convert string to integer with Integer.parseInt() function.
Java String to int Example
public class StringtoInt { public static void main(String[] args) { String str = "4"; int in = Integer.parseInt(str); System.out.println(in); } }
Output:
4
Note:
- parseInt() will convert string “4” to integer
- In order to use Integer.parseInt() method, we should pass string having numbers only. If input string contains other than numbers parseInt() function will throw java.lang.NumberFormatException. Would you like to see this scenario with an example ? 🙂 …
public class StringtoInt { public static void main(String[] args) { String str = "4s"; int in = Integer.parseInt(str); System.out.println(in); } }
Output:
Exception in thread “main” java.lang.NumberFormatException: For input string: “4s”
           at java.lang.NumberFormatException.forInputString(Unknown Source)
          at java.lang.Integer.parseInt(Unknown Source)
          at java.lang.Integer.parseInt(Unknown Source)
          at StringtoInt.main(StringtoInt.java:10)
​ ​​
You Might Also Like
::. About the Author .:: | ||
Comments
One Response to “How to Convert String to int in Java”
Nice explanation about String to int conversion in java.
thanks for this useful article.