How do I convert a String to an int in Java?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In Java, you can convert a String to an int using several methods. Below are the most common approaches:
1. Using Integer.parseInt()
The Integer.parseInt() method is the most straightforward way to convert a String to an int.
Example:
Handling Exceptions:
If the input string is not a valid integer, it throws a NumberFormatException.
2. Using Integer.valueOf()
The Integer.valueOf() method also converts a String to an int, but it returns an Integer object (not a primitive int).
Example:
- Auto-unboxing happens when assigning an
Integerobject to a primitiveint.
3. Using Integer.decode()
Integer.decode() can parse numbers from a String, including those with prefixes like "0x" (hexadecimal), "0" (octal), or plain decimal numbers.
Example:
4. Using parseInt() with a Radix
If the string represents a number in a specific base (radix), you can use Integer.parseInt() with a second argument for the radix.
Example:
5. Using Scanner Class
You can use the Scanner class to read and parse integers from strings.
Example:
Summary Table
| Method | Description | Output |
Integer.parseInt() | Converts String to primitive int. | Primitive int |
Integer.valueOf() | Converts String to Integer object. | Integer object |
Integer.decode() | Parses numbers in decimal, octal, or hexadecimal formats. | Primitive int |
parseInt(String, radix) | Converts String to int with a specified base (radix). | Primitive int |
Scanner.nextInt() | Parses integers using the Scanner class. | Primitive int |
Notes:
- Always handle
NumberFormatExceptionwhen converting strings to integers to ensure the input is valid. - Use
Integer.parseInt()for most cases where you need a primitiveint.
By choosing the appropriate method, you can safely and effectively convert a String to an integer in Java. 🚀

