Java - Convert a String to int
In Java, to convert a String to int, you can use Integer.parseInt() or Integer.valueOf().Example of Integer.parseInt()
String nombre_str = "22";Runtime:
int number = Integer.parseInt(nombre_str);
System.out.println(number);
22
Example of Integer.valueOf()
The Integer.valueOf() will return an object Integer.String nombre_s="22";Execution
int number = Integer.valueOf(nombre_s);
System.out.println(number);
22
In case the string is not accepted because it contains an alphabetic character, for example, a NumberFormatException will be triggered.
String nombre_s="9Ab";Output:
int number = Integer.parseInt(nombre_s);
System.out.println(number);
Exception in thread "main" java.lang.NumberFormatException: For input string: "9Ab"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
Resources:
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(java.lang.String, int)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String) a>