Java String to Int
This article shows how to convert a Java string to int .
To convert a Java String that represents an integer value, to the int type, one can use the utility methods of the Integer class.
Convert Java string to int using Integer.parseInt()
1 2 3 4 |
String numberAsString = "55"; int numberAsInt = Integer.parseInt(numberAsString); System.out.println(numberAsInt); |
Output
1 2 |
55 |
Alternatively, you can also use the Integer.valueOf() to achieve the same.
Convert Java string to int using Integer.valueOf()
1 2 3 4 |
String numberAsString = "21"; int numberAsInt = Integer.valueOf(numberAsString); System.out.println(numberAsInt); |
Output
1 2 |
21 |
However, if the string does not represent a integer value then any attempt to convert such a string to int would throw java.lang.NumberFormatException.
Converting a non-integer string
1 2 3 4 |
String numberAsString = "abcd"; int numberAsInt = Integer.valueOf(numberAsString); System.out.println(numberAsInt); |
Output
1 2 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "abcd" |
Subscribe
Login
0 Comments