1 String number = "10";
2 int result = Integer.parseInt(number);
3 System.out.println(result);
4Copy
1// You will receive an error if there are non-numeric characters in the String.
2String num = "5";
3int i = Integer.parseInt(num);
1public class JavaStringToIntExample
2{
3 public static void main (String[] args)
4 {
5 // String s = "fred"; // use this if you want to test the exception below
6 String s = "100";
7
8 try
9 {
10 // the String to int conversion happens here
11 int i = Integer.parseInt(s.trim());
12
13 // print out the value after the conversion
14 System.out.println("int i = " + i);
15 }
16 catch (NumberFormatException nfe)
17 {
18 System.out.println("NumberFormatException: " + nfe.getMessage());
19 }
20 }
21}