VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-convert-string-to-int-in-java/

⇱ String to int in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

String to int in Java

Last Updated : 23 Jul, 2025

Converting a String to an int in Java can be done using methods provided in the Integer class, such as Integer.parseInt() or Integer.valueOf() methods.

Example:

The most common method to convert a string to a primitive int is Integer.parseInt(). It throws a NumberFormatException if the string contains non-numeric characters.


Output
12345

Other Ways to Convert String to int

Using Integer.valueOf() Method

The Integer.valueOf() method converts a String to an Integer object instead of a primitive int. We can unbox it to an int.

Note: valueOf() method uses parseInt() internally to convert to integer. 

Example:


Output
217


Handling Errors for Non-Numeric Strings

If a string literal does not contain numeric values, calling the Integer.parseInt() or Integer.valueOf() methods will result in a NumberFormatException.

Example:

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at StringToIntExample.main(StringToIntExample.java:10)
Comment