Convert String to int in Java
In Java, you can use Integer.parseInt() to convert a String to int.
1. Integer.parseInt() Examples
Example to convert a String “10” to an primitive int.
1 2 3 |
String number = "10"; int result = Integer.parseInt(number); System.out.println(result); |
Output:
1 |
10 |
2. Integer.valueOf() Examples
Alternatively, you can use Integer.valueOf(), it will returns an Integer object.
1 2 3 |
String number = "10"; Integer result = Integer.valueOf(number); System.out.println(result); |
Output
1 |
10 |
3. NumberFormatException
If the string does not contain a parsable integer, a NumberFormatException will be thrown.
1 2 3 4 |
String number = "10A"; int result = Integer.parseInt(number); System.out.println(result);<code> |
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "10A"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)