How to convert from String to int in Java ?

In Java projects, conversion between String to int is required very frequently.Below is the different ways to convert from String to int in Java .

We will convert below String

How to convert String to int in Java ?
               String stringNumber= "51";

Using Integer.parseInt(String s) 


int convertedNum1=         Integer.parseInt(stringNumber);

System.out.println(convertedNum1);

Using Integer.valueOf(String s)

int convertedNum2= Integer.valueOf(stringNumber);

System.out.println(convertedNum2);


If String is not parsable it throws below NumberFormatException in both cases

Exception in thread "main" java.lang.NumberFormatException: For input string: "51A"

Output:

51


Date and Time operation in Java

Give your suggestion in comments.
If you like the post Share with your friends on social network.



How to convert from String to int in Java ? How to convert from String to int in Java ? Reviewed by JavaInstance on 9:03:00 AM Rating: 5

1 comment:

Powered by Blogger.