We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.
Program: String to int example
Following example demonstrates the Java String to int conversion process, handling for a possible NumberFormatException:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class JavaStringToIntExample { public static void main (String[] args) { // String s = "fred"; // use this if you want to test the exception below String s = "100"; try { // the String to int conversion happens here int i = Integer.parseInt(s.trim()); // print out the value after the conversion System.out.println("int i = " + i); } catch (NumberFormatException nfe) { System.out.println("NumberFormatException: " + nfe.getMessage()); } } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.