How do I convert a String to an int in Java?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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. 🚀
Related reading
- How do I efficiently iterate over each entry in a Java Map?
- How do I generate random integers within a specific range in Java?
- How do I read / convert an InputStream into a String in Java?
- Java, How to get number of messages in a topic in apache kafka
- What is the difference between public, protected, package-private and private in Java?
- / and / in Java Comments
- (double colon) operator in Java 8
- Plus sign not encoded with RestTemplate using String URL, interpreted as space

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.