Java String to int Example Code for Convert string to int with Java
Content about : Java String to int
Advertisements
Example for Convert String to int with Java
package example;
public class StringToIntExample {
public void stringToInt(String input){
try {
//Convert with Integer.parseInt(input);
int intvalue=Integer.parseInt(input);
System.out.println(”int value:”+(intvalue+100));
//Convert with Integer.valueOf(input);
int intvalue2=Integer.valueOf(input);
System.out.println(”int value:”+(intvalue2+200));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
StringToIntExample stringToIntExample=new StringToIntExample();
stringToIntExample.stringToInt(”500″);
}
}
Running Result
int value:600
int value:700
**If String value sent to stringToInt method not NumberFormat it will throws Exception **
java.lang.NumberFormatException: For input string: “500q”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at example.StringToIntExample.stringToInt(StringToIntExample.java:7)
at example.StringToIntExample.main(StringToIntExample.java:18)