Various ways to convert String to Integer in java

[1452 views]




There are 2 ways by which you can convert String to Integer. Both methods are defined in Integer class. They are:

  1. Using Integer.parseInt(String)
  2. Using Integer.valueOf(String)

Let's see an example of both:

Conversion Using Integer.parseInt(String):

public class ConvertStrToInt { public static void main(String[] args) { String number = "99"; try{ // String to integer int result = Integer.parseInt(number); // 99 System.out.println(result); } catch (NumberFormatException e) { //handle exception as you want System.err.println("Invalid format : " + number); } } }

Conversion Using Integer.valueOf(String):

public class ConvertStrToInt { public static void main(String[] args) { String number = "99"; try{ // String to integer Integer result = Integer.valueOf(number); // 99 System.out.println(result); }catch (NumberFormatException e) { //handle exception as you want System.err.println("Invalid format : " + number); } } }

As you can see in both of the Examples above, converts a String to an Integer, so the only difference between the two is that the Integer.parseInt(String) method converts a String to primitive type int; whereas the Integer.valueOf(String) method convert a String to a Integer object.

Also, Always add above code in a try-catch block like we have added, as it can throw a NumberFormatException for unparsable String.

                  Liked Article? Please Buy me a Coffee 😭



Want to Clear Java Interview? Read Java Interview Notes prepared by Us


Are You Good enough in Java?



Learn Python in a Week and Master It

Comments








Search
Need Programming Help??


Below Offers ends in













Quiz For You:

Search Tags

    Convert String to Int in Java