Java Convert String to int : In Java, you can use Integer.parseInt()
to convert a String to int.
Using : Integer.parseInt()
Java Convert String to int : In this exemple we are trying to convert “10” to primitive int
String number = "10"; int result = Integer.parseInt(number); System.out.println(result);
Output :
10
Using : Integer.valueOf()
The difference here is that Integer.valueOf() it will returns an Integer object.
String number = "10"; Integer result = Integer.valueOf(number); System.out.println(result);
Output :
10
If the string does not contain a parsable integer, a NumberFormatException will be thrown !!!
String number = "10A"; int result = Integer.parseInt(number); System.out.println(result);
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)
Lire aussi : Création d’un Projet JSF 2.2 dans eclipse
Recouvrir : infoUtiles
Pingback: Java 7 - Java 8 - loop Map / List - forEach examples » JavaTuto
Pingback: How to pad a String in Java ? » Exemple » JavaTuto
Pingback: long to int in Java : How can I convert a long to int in Java ? » JavaTuto