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
package com.projectsgeek; public class JavaExample { /** * @projectsgeek */ public static void main(String[] args) { //Convert String to int using Java String string = "99"; Integer StringResult = Integer.valueOf(string); System.out.print(StringResult); } }
Output
Input value is 99 in form of string which will be converted to int using valueOf() method.
99
Integer.parseInt() Examples
This method uses parseInt() method for converting string into int in java.
package com.projectsgeek; public class JavaExample { /** * @projectsgeek */ public static void main(String[] args) { //Converting String to int using Java String string = "99"; int stringResult = Integer.parseInt(string); System.out.print(stringResult); } }
Output
Input value is 99 again and this string value will be converted to int using parseInt() method.
99
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.
package com.projectsgeek; public class JavaExample { /** * @projectsgeek */ public static void main(String[] args) { //Converting String to int using Java String string = "99D"; int stringResult = Integer.parseInt(string); System.out.println(stringResult); } }
Output
java.lang.NumberFormatException is thrown as parseInt() is not able to convert 99D value to int.
Exception in thread "main" java.lang.NumberFormatException: For input string: "99D" [Passing non int value] at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at com.projectsgeek.JavaExample.main(JavaExample.java:12) [exception thrown while converting]
Reference
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
Leave a Reply