Javatpoint Logo
Javatpoint Logo

Java Convert String to int

We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.

Java Convert String to int

Scenario

It is generally used if we have to perform mathematical operations on the string which contains a number. Whenever we receive data from TextField or TextArea, entered data is received as a string. If entered data is in number format, we need to convert the string to an int. To do so, we use Integer.parseInt() method.

Signature

The parseInt() is the static method of Integer class. The signature of parseInt() method is given below:

Java String to int Example: Integer.parseInt()

Let's see the simple code to convert a string to an int in java.

Let's see the simple example of converting String to int in Java.

Test it Now

Output:

200

Understanding String Concatenation Operator

Test it Now

Output:

200100
300

Java String to Integer Example: Integer.valueOf()

The Integer.valueOf() method converts String into Integer object. Let's see the simple code to convert String to Integer in Java.

Test it Now

Output:

300

NumberFormatException Case

If you don't have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException.

Test it Now

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at StringToIntegerExample3.main(StringToIntegerExample3.java:4)

References

  1. Integer.parseInt() JavaDoc
  2. Integer.valueOf() JavaDoc
  3. NumberFormatException JavaDoc
Next TopicJava int to String




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials