Introduction
In this post, we will learn to convert String to int primitive data type. Java provides the Integer wrapper class to convert a String to int.Integer.parseInt(String)
int number = Integer.parseInt(numberString );
System.out.println(number);
Output: 134
Integer.valueOf(String)
String numberString = "134";
int number = Integer.valueOf(numberString );
System.out.println(number);
Output: 134
The following code will throw NumberFormatException
//134a cannot be converted to Integer
String numberString = "134a";
int number = Integer.valueOf(numberString );
System.out.println(number);
Exception in thread "main" java.lang.NumberFormatException: For input string: "134a"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at StringExample.main(StringExample.java:6)
Comments
Post a Comment