Java Integer parseInt() Method
Example
Convert a string to a number, and add 5 to it:
public class Main {
public static void main(String[] args) {
String text = "25";
int myNum = Integer.parseInt(text);
System.out.println(myNum + 5);
}
}
Definition and Usage
The parseInt() method converts a string to an int. The string must contain a whole number, like "25" or "-7".
If the string is not a whole number, for example "Hello" or "2.5", the method throws a NumberFormatException.
Tip: Use the second parameter to read numbers in other number systems. For example, Integer.parseInt("101", 2) returns 5, because 101 in binary is 5.
Syntax
One of the following:
public static int parseInt(String s)
public static int parseInt(String s, int radix)
Parameter Values
| Parameter | Description |
|---|---|
| s | Required. The string to convert. |
| radix | Optional. The base of the number system (the radix), for example 2 for binary or 16 for hexadecimal. The default is 10. |
Technical Details
| Returns: | The number in the string, as an int. |
|---|---|
| Throws: | NumberFormatException - if the string is not a whole number, or the number is too large for an int. |
Related Pages
❮ Integer Methods