The three ways to convert a string to an integer in Java
Java gives you three main methods to turn a string into an integer: Integer.parseInt(), Integer.valueOf(), and new Integer(). The first two are the ones you'll use in real code. Integer.parseInt() returns a plain integer value, while Integer.valueOf() returns an Integer object that wraps that value. The third method (new Integer()) still works but is considered outdated and most developers avoid it.
The choice between parseInt() and valueOf() matters only if your code needs to store the result in a variable that expects an object rather than a primitive value. For most situations, parseInt() is simpler and slightly faster. Both methods throw an exception if the string contains anything other than digits, an optional minus sign at the start, or whitespace at the edges.
Key Takeaways
- Integer.parseInt() converts a string directly to an int primitive and is the most common choice for everyday code.
- Integer.valueOf() does the same conversion but returns an Integer object instead, which matters only if your code requires an object type.
- Both methods throw a NumberFormatException if the string contains letters, special characters, or other non-numeric content.
- You can handle conversion errors by wrapping the conversion in a try-catch block to prevent your program from crashing.
- Whitespace at the beginning or end of the string is automatically ignored, but spaces in the middle will cause an error.
Using Integer.parseInt() for basic conversion
Integer.parseInt() is the standard choice when you need to convert a string to a simple integer value. The syntax is straightforward: you pass the string as an argument, and it returns an int. For example, Integer.parseInt("42") returns the integer 42, and Integer.parseInt("-17") returns -17.
The method automatically strips leading and trailing whitespace, so Integer.parseInt(" 99 ") works fine and returns 99. However, any non-numeric character in the middle of the string causes a NumberFormatException. If you try Integer.parseInt("12a34"), your program will crash unless you catch the exception.
You can also specify a radix (number base) as a second argument if you're working with binary, octal, or hexadecimal strings. For instance, Integer.parseInt("1010", 2) converts the binary string "1010" to the decimal integer 10. The radix can be any value from 2 to 36.
Using Integer.valueOf() when you need an object
Integer.valueOf() does the same conversion as parseInt() but returns an Integer object instead of a primitive int. This matters when your code expects an object—for example, when storing values in a collection like ArrayList or HashMap, or when passing the value to a method that requires an Integer object rather than an int.
The syntax is identical: Integer.valueOf("42") returns an Integer object with the value 42. Like parseInt(), it ignores leading and trailing whitespace, throws an exception on invalid input, and accepts an optional radix argument for different number bases.
One practical difference: Integer.valueOf() caches values between -128 and 127, meaning repeated calls with the same string in that range may return the same object in memory. This is an optimization detail that rarely matters in real programs, but it's why valueOf() can be slightly slower than parseInt() on the first call for a new value.
Handling errors when conversion fails
Both parseInt() and valueOf() throw a NumberFormatException if the string cannot be converted. This exception stops your program unless you catch it. The most common approach is to wrap the conversion in a try-catch block:
In the try block, you attempt the conversion. In the catch block, you handle the error—either by using a default value, logging the problem, or asking the user to enter valid input. For example, you might catch the exception and set the integer to 0, or display an error message and ask the user to try again.
Another approach is to check the string before converting it. You can use methods like String.matches() with a regular expression to verify the string contains only digits and an optional minus sign before calling parseInt(). This prevents the exception from being thrown in the first place, though it requires writing and understanding a regular expression pattern.
Common mistakes and how to avoid them
The most frequent error is forgetting to handle the NumberFormatException. If you call Integer.parseInt() on user input without a try-catch block and the user enters letters or symbols, your program crashes. Always wrap conversions of untrusted input in error handling.
Another common mistake is confusing the string "null" with an actual null value. If you pass the string "null" to parseInt(), it throws an exception—the method doesn't recognize it as a special case. If your variable might be null, check for that separately before attempting conversion.
People also sometimes forget that parseInt() and valueOf() are static methods called on the Integer class itself, not on the string. The correct syntax is Integer.parseInt(myString), not myString.parseInt(). Reversing this order causes a compilation error.
When to use each method in real code
Use Integer.parseInt() as your default choice. It's the most straightforward, performs well, and is what most Java developers expect to see. Use it whenever you need a simple int value from a string.
Use Integer.valueOf() when your code specifically requires an Integer object—for instance, when adding values to an ArrayList<Integer> or passing the result to a method with an Integer parameter. Java's autoboxing feature automatically converts between int and Integer in most situations, so you rarely need to think about this distinction.
Avoid new Integer() entirely. It's an older syntax that still works but serves no purpose now that autoboxing exists. Modern Java style guides recommend against it, and code reviewers will flag it as outdated.
Converting strings with different number formats
If your string represents a number in a base other than decimal, use the radix parameter. Integer.parseInt("FF", 16) converts the hexadecimal string "FF" to 255. Integer.parseInt("77", 8) converts the octal string "77" to 63. The radix must be between 2 and 36.
For very large numbers that exceed the range of an int (which goes up to 2,147,483,647), use Long.parseLong() instead. The syntax is identical, but it returns a long value that can hold much larger numbers. If you need even larger numbers, the BigInteger class handles arbitrary precision, though it requires more complex syntax.
Strings with decimal points like "3.14" cannot be converted directly with parseInt() or valueOf()—they throw an exception. If you need to convert a decimal string, use Double.parseDouble() or Float.parseFloat() instead, then cast the result to int if you need an integer.
Frequently Asked Questions
What's the difference between parseInt and valueOf?
parseInt() returns a primitive int value, while valueOf() returns an Integer object. For most code, parseInt() is simpler and faster. Use valueOf() only when you specifically need an object type, such as storing values in a collection that requires objects.
Why does my code crash when I convert a string with letters?
Both parseInt() and valueOf() throw a NumberFormatException when the string contains non-numeric characters. Wrap the conversion in a try-catch block to handle the error, or check the string's contents before converting it.
Can I convert a string like "3.14" to an integer?
No, parseInt() and valueOf() reject decimal points. Use Double.parseDouble() to convert "3.14" to 3.14, then cast it to int (which gives you 3) if you need an integer. Alternatively, use a method like Math.round() to round the decimal value first.
Does whitespace in the string cause problems?
Whitespace at the beginning or end is automatically ignored, so " 42 " converts fine. Whitespace in the middle causes an exception, so "4 2" will fail.
What's the maximum integer I can convert?
An int in Java ranges from -2,147,483,648 to 2,147,483,647. If your string represents a larger number, use Long.parseLong() instead, which handles values up to 9,223,372,036,854,775,807.