parseInt() Method in Java

There are two variants of this method:

  1. parseInt(String s): This function parses the string argument as a signed decimal integer.
  2. parseInt(String s, int radix): This function parses the string argument as a signed integer in the radix specified by the second argument.

Syntax of parseInt

public static int parseInt(String str); 
public static int parseInt(String str, int radix);

Parameters

  • str: String that needs to be converted to an integer.
  • radix: is used while the string is being parsed.

Return Type

  • Both methods convert the string into its integer equivalent. The only difference is that of the parameter radix. The first method can be considered with radix = 10 (Decimal).

Exception Thrown

Remember certain key points associated with both variants:

  1. The string can be null or of zero-length
  2. Value represented by the string is not a value of type int
  3. Specifically for the parseInt(String s, int radix) variant of the function: 
    • The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX
    • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1
  4. If your String has leading zeroes, the parseInt() method will ignore them. 

String to int in Java

In Java, while operating upon strings, there are times when we need to convert a number represented as a string into an integer type. We usually do this because we can operate with a wide flexible set of operations over strings. The method generally used to convert String to Integer in Java is parseInt() of the String class.

In this article, we will see how to convert a String to int in Java.

Similar Reads

Program to Convert Java String to int

Let us take an example straight away to get used to the working parseInt() method :...

parseInt() Method in Java

...

Cases of parseInt() Method

There are two variants of this method:...

Number Format Exceptions of parseInt() Method

Let’s take a random code snippet further understand the illustrations better....

Another Approach for Converting a String to Integer

Exceptions caused by parseInt() Method mentioned below:...