Share with others

Convert String to int using Java

 

Using Integer.valueOf() in Java

This method uses valueOf() method to convert string into Integer object which we can use to print directly to console.

Source Code

Output

Input value is 99 in form of string which will be converted to int using valueOf() method.

Integer.parseInt() Examples

This method uses parseInt() method for converting string into int in java.

Output

Input value is 99 again and this string value will be converted to int using parseInt() method.

This method can convert any string value which is convertible to int. But what about values which you can’t convert to int for example “12d”,”aa” ? This java method will through exception when it is not able to convert it to int value.

Output

java.lang.NumberFormatException is thrown as parseInt() is not able to convert 99D value to int. 

Reference 

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)


Share with others