How to convert string to int in java

In this article you are going to learn, how to convert string to int in Java.

  1. parseInt
  2. valueOf
  3. NumberFormatException

1. Integer.parseInt():

String str = “50”;
int num= Integer.parseInt(str);
System.out.println(num);

Output:

50

Info: It parses the string argument as a decimal integer. All characters in the string must be integers. Otherwise it will throw NumberFormatException.

2. Integer.valueOf():

String str = “99”;
Integer num = Integer.valueOf(str);
System.out.println(num);

Output:

99

Info: It returns an Integer object holding the value of the string. If the string does not contain a parsable integer, it will throw NumberFormatException.

3. NumberFormatException:

NumberFormatException exception will be thrown if string doesn’t contain a parsable integer.

public void numberFormatException(){
String str = “99A“;
int num = Integer.parseInt(str);
System.out.println(num);
}

Output:

Exception in thread “main” java.lang.NumberFormatException: For input string: “99A”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)

Other links:

How to select a dropdown using selenium web driver

Top 25 selenium interview questions

How to take screenshot in Selenium WebDriver

How to handle alerts in Selenium WebDriver

Implicit wait and Explicit wait in Selenium

Tags: String to int in java, selenium webdriver, parseInt, selenium tutorials

2 thoughts on “How to convert string to int in java

Leave a Reply

Your email address will not be published.