Skip to content

Java convert String to int example

Java String to int example shows how to convert string to int in Java using the parseInt method of the Integer wrapper class including the NumberFormatException.

How to convert String to int in Java?

To convert a string to int, we can use the parseInt method of the Java Integer wrapper class.

This method returns an int primitive value by parsing the input string value.

Output

Important Note:

All the characters in the string must be a digit, except for the first character of the string which can be a “-” (minus sign) to indicate the negative numeric value.

If any of the characters in the string (except for the first character, if it is a minus sign) is a non-digit character, the NumberFormatException is thrown while converting the string to an int value.

Output

Here are some of the example string values and their possible outputs.

Please note that the “+” (plus sign) is allowed as the first character of the string only in the newer versions of Java. In older versions, if the string has a plus sign as the first character, the parseInt method throws a NumberFormatException exception.

This example is a part of the Java Basic Examples and Java Type conversion Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.