In Java we can convert string to integer with Integer.parseInt() function.
Example:
In order to use Integer.parseInt() method, we should pass string numbers only. If input string contains other than numbers parseInt() function will throw java.lang.NumberFormatException.
Syntax:
int in = Integer.parseInt(str);
package com.tutorial4u;
public class StringToInt {
public static void main(String[] args) {
String str = "4";
int in = Integer.parseInt(str);
System.out.println(in);
}
}
Output: 4
Note:
Example:
package com.tutorial4u;
public class StringToInt {
public static void main(String[] args) {
String str = "Tutorial4u";
int in = Integer.parseInt(str);
System.out.println(in);
}
}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Tutorial4u"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.tutorial4u.StringToInt.main(StringToInt.java:6)