Various ways to convert String to Integer in java

[1158 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.

                 



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


Are You Good enough in Java? Prove it!



Comments



Search

Need Freelance Programming Writers, Contact us now at atechdailyweb@gmail.com




Having Programming Doubts or Facing any Issues?


Hurry Up! Exclusive Deals For You ends in















Quiz For You:
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    Convert String to Int in Java