Various ways to convert String to Integer in java

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

                 




Comments



Search

For any inquiry, Contact us at atechdailyweb@gmail.com




Facing Programming Errors. Get Answers within 24 hours:


Recommendation Based on your Interest




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

Search Tags

    Convert String to Int in Java