Use Integer.valueOf()method to convert string to integer object.
/** * @author lautturi.com * Java example: Convert string to int in Java */ import java.util.*; public class Lautturi { public static void main(String[] args) { String str = "123"; Integer result = Integer.valueOf(str); System.out.print(result); } }
output:
123
If we try to convert a string which has no numbers,we will get the NumberFormatException:
import java.util.*; public class Lautturi { public static void main(String[] args) { String str = "abcd"; Integer result = Integer.valueOf(str); System.out.print(result); } }
output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "abcd" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.valueOf(Integer.java:983)