How to convert string to int in java

By | May 9, 2020

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);



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);



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);


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)

Related articles:

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

Leave a Reply

Your email address will not be published. Required fields are marked *