Convert String to int utilizing Java
Utilizing Integer.valueOf() in Java
This technique makes use of valueOf() technique to transform string into Integer object which we will use to print on to console.
Supply Code
1 |
package deal com.projectsgeek;<br/><br/>public class JavaExample {<br/><br/>/**<br/>* @projectsgeek<br/>*/<br/>public static void important(String[] args) {<br/><br/>//Convert String to int utilizing Java<br/>String string = "99";<br/>Integer StringResult = Integer.valueOf(string);<br/>System.out.print(StringResult);<br/>}<br/>} |
Output
Enter worth is 99 in type of string which will likely be transformed to int utilizing valueOf() technique.
1 |
99 |
Integer.parseInt() Examples
This technique makes use of parseInt() technique for changing string into int in java.
1 |
package deal com.projectsgeek;<br/><br/>public class JavaExample {<br/><br/>/**<br/>* @projectsgeek<br/>*/<br/>public static void important(String[] args) {<br/><br/>//Changing String to int utilizing Java<br/>String string = "99";<br/>int stringResult = Integer.parseInt(string);<br/>System.out.print(stringResult);<br/>}<br/>} |
Output
Enter worth is 99 once more and this string worth will likely be transformed to int utilizing parseInt() technique.
1 |
99 |
This technique can convert any string worth which is convertible to int. However what about values which you’ll’t convert to int for instance “12d”,”aa” ? This java technique will by way of exception when it’s not in a position to convert it to int worth.
1 |
package deal com.projectsgeek;<br/><br/>public class JavaExample {<br/><br/>/**<br/>* @projectsgeek<br/>*/<br/>public static void important(String[] args) {<br/><br/>//Changing String to int utilizing Java<br/>String string = "99D";<br/>int stringResult = Integer.parseInt(string);<br/>System.out.println(stringResult);<br/>}<br/>} |
Output
java.lang.NumberFormatException is thrown as parseInt() just isn’t in a position to convert 99D worth to int.
1 |
Exception in thread "important" java.lang.NumberFormatException: For enter string: "99D" [Passing non int value]<br/>at java.lang.NumberFormatException.forInputString(Unknown Supply)<br/>at java.lang.Integer.parseInt(Unknown Supply)<br/>at java.lang.Integer.parseInt(Unknown Supply)<br/>at com.projectsgeek.JavaExample.important(JavaExample.java:12) [exception thrown while converting] |
Reference
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
Supply projectgeek.com