The three ways to turn a string into an integer in Java
Java gives you three main paths to convert a string to an integer: Integer.parseInt(), Integer.valueOf(), and new Integer(). The first two are what you'll use in real code. Integer.parseInt() returns a primitive int value and is the fastest choice when you just need the number itself. Integer.valueOf() returns an Integer object (the wrapper class) and caches small values, making it useful if you're storing the result in a collection or passing it to a method that expects an object.
The difference matters because Java distinguishes between primitive types (like int, which holds just a number) and objects (like Integer, which wraps that number in a class). For most everyday conversions, Integer.parseInt() is the right pick. The third option, new Integer(), still works but is considered outdated — Java's documentation recommends valueOf() instead.
Key Takeaways
- Integer.parseInt() converts a string to a primitive int and is the fastest method for straightforward number conversion.
- Integer.valueOf() converts a string to an Integer object and caches values between -128 and 127, making it efficient for repeated conversions of small numbers.
- Both methods throw a NumberFormatException if the string contains non-numeric characters or is empty, so you need to handle that error.
- Whitespace at the start or end of a string is ignored, but spaces in the middle will cause the conversion to fail.
Using Integer.parseInt() for basic conversion
Integer.parseInt() is the straightforward choice when you need a plain integer from a string. The syntax is straightforward: you pass the string as an argument, and it returns an int. For example, Integer.parseInt("42") returns the number 42, not a string anymore.
The method also accepts a second argument for the number base (called the radix). Integer.parseInt("1010", 2) converts the binary string "1010" to 10 in decimal. Integer.parseInt("FF", 16) converts the hexadecimal string "FF" to 255. This is useful when you're reading data in different formats, though base 10 (the default) covers most cases.
If the string cannot be converted — because it contains letters, symbols, or is completely empty — Integer.parseInt() throws a NumberFormatException. You must catch this error or declare that your method throws it. A try-catch block is the standard way to handle it:
try { int number = Integer.parseInt("42"); } catch (NumberFormatException e) { System.out.println("That's not a valid number"); }
Using Integer.valueOf() when you need an object
Integer.valueOf() does the same conversion but wraps the result in an Integer object. This matters when you're storing values in a list, map, or other collection that expects objects rather than primitives. It also matters when a method signature requires an Integer parameter instead of an int.
Integer.valueOf() has a built-in optimization: it caches Integer objects for values between -128 and 127. If you convert "50" to an Integer ten times, valueOf() returns the same cached object each time rather than creating a new one. This saves memory and makes the code slightly faster when you're converting small numbers repeatedly. Integer.parseInt() has no such cache because it returns a primitive, not an object.
Like parseInt(), valueOf() throws a NumberFormatException if the string is invalid. The error handling is identical:
try { Integer number = Integer.valueOf("42"); } catch (NumberFormatException e) { System.out.println("That's not a valid number"); }
Handling errors when conversion fails
Both parseInt() and valueOf() fail silently in one sense: they don't return a default value or a null. Instead, they throw an exception that stops your program unless you catch it. This is intentional — it forces you to decide what to do when bad data arrives.
The most common approach is a try-catch block that catches NumberFormatException specifically. You can then log the error, use a default value, ask the user to re-enter the data, or skip that record. A second approach is to declare that your method throws the exception, passing the responsibility up to whoever called your code — this works when the caller is better positioned to handle the error.
A third approach, less common but sometimes useful, is to check the string before converting. You can use a regular expression or a straightforward loop to verify that every character is a digit (and handle a leading minus sign for negative numbers). This prevents the exception from being thrown in the first place, though it adds code and is usually slower than just catching the exception.
Converting negative numbers and handling whitespace
Both parseInt() and valueOf() handle negative numbers automatically. Integer.parseInt("-42") returns -42. The minus sign must come first, when ready before the digits, with no space between them.
Whitespace at the very start or very end of the string is automatically trimmed. Integer.parseInt(" 42 ") works fine and returns 42. However, any space in the middle breaks the conversion: Integer.parseInt("4 2") throws a NumberFormatException. This is a common source of bugs when you're reading data from files or user input that may have unexpected formatting.
If you suspect your string might have internal spaces or other formatting issues, clean it before converting. The trim() method removes leading and trailing whitespace, and replace() can remove spaces from the middle if needed.
Choosing between parseInt() and valueOf()
Use Integer.parseInt() when you need a primitive int — when you're doing math, storing the value in an array of primitives, or passing it to a method that expects an int parameter. It's slightly faster and uses less memory because it doesn't create an object wrapper.
Use Integer.valueOf() when you need an Integer object — when you're storing values in a collection like ArrayList or HashMap, or when a method signature requires an Integer. The caching of small values is a bonus that makes repeated conversions more efficient.
In practice, the performance difference between the two is negligible for most applications. The real choice is about what your code needs: a primitive or an object. If you're unsure, parseInt() is the safer default because it's simpler and more commonly used.
Frequently Asked Questions
What happens if I try to convert a string with decimal points?
Both parseInt() and valueOf() throw a NumberFormatException. They only handle whole numbers. If you need to convert "42.5" to a number, use Double.parseDouble() or Float.parseFloat() instead, then cast or round the result if you need an integer.
Can I convert a string that's too large for an int?
No. An int in Java holds values from -2,147,483,648 to 2,147,483,647. If your string represents a larger number, parseInt() and valueOf() throw a NumberFormatException. Use Long.parseLong() for larger values, or BigInteger if you need even bigger numbers.
Is there a way to convert without throwing an exception?
Not with parseInt() or valueOf() directly. You can write a helper method that catches the exception and returns a default value (like 0) if conversion fails. Some developers use try-catch blocks inline, while others wrap the conversion in a utility function that handles the error and returns a sensible fallback.
Why does Integer.valueOf() cache small numbers?
Caching improves performance and memory use when the same small values are converted repeatedly. Since -128 to 127 are common in many programs, Java pre-creates those Integer objects once and reuses them. Larger numbers get new objects each time, but the overhead is minimal.
Can I specify a different number base when using valueOf()?
No. Integer.valueOf() always assumes base 10. If you need to convert from binary, hexadecimal, or another base, use Integer.parseInt() with the radix argument instead: Integer.parseInt("1010", 2) for binary or Integer.parseInt("FF", 16) for hexadecimal.