We can convert a string to int in two ways, first using Integer.parseInt() method, and the second is using Integer.valueOf(), the difference between the two approaches is that the second method return an instance of integer class object.
The parseInt() is a static method of the Integer class,here is the example to use it to convert a string to int
1 2 3 4 5 |
public void test(){ String s="12345"; int result = Integer.parseInt(s); System.out.print(result) } |
the output is
1 |
12345 |
Let’s see the example of the second method Integer.valueOf() to convert string to integer object.
1 2 3 4 5 |
public void test(){ String s="12345"; Integer result = Integer.valueOf(s); System.out.print(result) } |
Please note that if we try to convert a string which has no numbers use the Integer.parseInt() or Integer.valueOf() methods,will get the NumberFormatException,for example
1 2 3 4 5 |
public void test(){ String s="asenview"; Integer result = Integer.valueOf(s); System.out.print(result) } |
The output is
1 2 3 4 5 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "asenview" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at StringToIntegerExample3.main(StringToIntegerExample3.java:4) |