Convert String to Int in Java with examples
Contents
Integer.parseInt()
We can convert the String value to int in Java using Integer.parseInt() method. If the String variable contains only numbers and you want to return a value as int, this Integer.parseInt() will help you on this.
Convert String to Int (String variable contains only numbers)
1 2 3 4 5 6 7 |
public class ConvertStringToInt { public static void main(String[] args) { String str_num = "15"; int result = Integer.parseInt(str_num); System.out.println(result); } } |
Output
1 |
15 |
Integer.valueOf() method:
The Integer.valueOf() method helps to convert the String to Integer Object. If you want to convert the Integer Object to int value,you can use intValue() method on the Integer Object.
1 2 3 4 5 6 7 8 9 |
public class ConvertStringToInt { public static void main(String[] args) { String str_num = "15"; Integer result = Integer.valueOf(str_num); System.out.println(result); int number = result.intValue(); System.out.println(number); } } |
Output:
1 2 |
15 15 |
NumberFormatException
If the String variable contains both String and numbers, the Integer.parseInt() will throw an Number format exception error as below.
1 2 3 |
String str_num = "15R"; int result = Integer.parseInt(str_num); System.out.println(result); |
Output:
1 2 3 4 5 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "15R" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at testJavaExamples.ConvertStringToInt.main(ConvertStringToInt.java:7) |
Recommended Articles
- How to convert kilometers to miles using Java program?
- Convert bytes to KB,MB and GB using Java Program