Monday, 3 June 2019

Java | Convert String to int

In Java, Integer.parseInt() method can be used to convert a String to int.

1. Integer.parseInt() Examples
Example to convert a String “10” to a primitive int.

      String number = "20";
      int result = Integer.parseInt(number);               
      System.out.println(result);

Output
20

2. Integer.valueOf() Examples
Alternatively, we can use Integer.valueOf(), it will return an Integer object.

      String number = "20";
      int result = Integer.valueOf(number);                
      System.out.println(result);

Output
20

3. NumberFormatException
If String does not contain a parsable integer, a NumberFormatException will be thrown.

      String number = "20A";
      int result = Integer.parseInt(number);               
      System.out.println(result);

Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "20A"
      at java.lang.NumberFormatException.forInputString(Unknown Source)
      at java.lang.Integer.parseInt(Unknown Source)
      at java.lang.Integer.valueOf(Unknown Source)


Note
In precis, parseInt(String) returns a primitive int, whereas valueOf(String) returns a new Integer() object.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...