Java : Convert String to int

java-string-to-int

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

Marwen Mselmi
Author: Marwen Mselmi

Founder of Javatuto.com, love Java and open source stuff. Follow me on Linkedin.

Leave a comment