parseInt() Method in Java
There are two variants of this method:
- parseInt(String s): This function parses the string argument as a signed decimal integer.
- 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
- NumberFormatException is thrown by this method if any of the following situations occur.
Remember certain key points associated with both variants:
- The string can be null or of zero-length
- Value represented by the string is not a value of type int
- 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
- 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.