The most common ways to convert a string to an integer in Java

Java gives you four main paths to turn a string into an integer: Integer.parseInt(), Integer.valueOf(), Integer.decode(), and the Integer class constructor. The first two handle the vast majority of real code. Integer.parseInt() is the fastest and most direct — it takes a string like "42" and returns the integer 42. Integer.valueOf() does the same thing but wraps the result in an Integer object, which matters if your code needs an object rather than a primitive value.

The choice between them depends on what your code does next. If you need a primitive int, use parseInt(). If you need an Integer object (because you're putting it in a collection, for instance), use valueOf(). Both throw a NumberFormatException if the string contains anything that is not a valid number.

Key Takeaways

  • Integer.parseInt("42") converts a string to a primitive int and is the fastest option for most situations.
  • Integer.valueOf("42") converts a string to an Integer object, which is necessary when you need to store the value in a collection or pass it to a method expecting an object.
  • Both methods throw NumberFormatException if the string contains non-numeric characters, so wrap them in a try-catch block if the input is not may provide to be valid.
  • Integer.decode() handles strings with prefixes like "0x" for hexadecimal, but parseInt() and valueOf() do not recognize these prefixes by default.

Using Integer.parseInt() for primitive integers

Integer.parseInt() is the standard choice when you need a primitive int value. The method takes a string and returns an int directly. The simplest form is parseInt(String s), which assumes the string represents a decimal number:

String input = "42";int result = Integer.parseInt(input);System.out.println(result); // prints 42

If your string has leading or trailing whitespace, parseInt() strips it automatically, so " 42 " works fine. Negative numbers work too: Integer.parseInt("-42") returns -42. The method also accepts a second parameter for the radix (base) if you need to parse binary, octal, or hexadecimal strings. For example, Integer.parseInt("1010", 2) converts the binary string "1010" to the decimal integer 10.

When the string is not a valid number, parseInt() throws NumberFormatException. If you are not certain the input is valid, wrap the call in a try-catch block to handle the error gracefully.

Using Integer.valueOf() for Integer objects

Integer.valueOf() does the same conversion as parseInt() but returns an Integer object instead of a primitive int. Use this when your code needs an object — for instance, when storing values in an ArrayList or HashMap, or when passing the value to a method that expects an Integer rather than an int.

String input = "42";Integer result = Integer.valueOf(input);System.out.println(result); // prints 42

The behavior is nearly identical to parseInt(): it strips whitespace, handles negative numbers, and accepts a radix parameter. Integer.valueOf("1010", 2) also returns an Integer object representing 10. Like parseInt(), it throws NumberFormatException if the string is invalid.

One subtle difference: valueOf() caches Integer objects in the range -128 to 127. If you convert the same string multiple times within that range, valueOf() may return the same object from memory rather than creating a new one. This is an optimization detail that rarely matters in practice, but it means valueOf() can be slightly more memory-efficient for repeated conversions of small numbers.

Handling invalid input with try-catch

Both parseInt() and valueOf() throw NumberFormatException when the string cannot be converted. If your input comes from a user, a file, or any untrusted source, you should catch this exception:

String input = getUserInput();try {  int result = Integer.parseInt(input);  System.out.println("Converted: " + result);} catch (NumberFormatException e) {  System.out.println("Invalid number: " + input);}

This pattern prevents your program from crashing when it encounters unexpected input. You can log the error, prompt the user to try again, or use a default value depending on what your application needs to do.

Parsing strings with number prefixes using Integer.decode()

Integer.decode() handles strings that start with a prefix indicating the number base. It recognizes "0x" or "0X" for hexadecimal, "0" for octal, and no prefix for decimal. This is useful when you are reading formatted data that includes these prefixes:

Integer hex = Integer.decode("0xFF"); // returns 255Integer octal = Integer.decode("077"); // returns 63Integer decimal = Integer.decode("42"); // returns 42

Like parseInt() and valueOf(), decode() throws NumberFormatException if the string is malformed. It always returns an Integer object, not a primitive int, so if you need a primitive you must unbox it or cast it. For most everyday code, parseInt() or valueOf() with an explicit radix parameter is clearer than decode(), but decode() is the right choice when you are parsing data that already includes these prefixes.

The Integer constructor approach (deprecated)

Older Java code sometimes uses the Integer constructor directly: new Integer("42"). This works but is now marked as deprecated in modern Java versions. The reason is that valueOf() does the same thing and is preferred because it can cache small values more efficiently. If you encounter this pattern in existing code, it still works, but new code should use valueOf() instead.

The deprecation does not mean the constructor will disappear soon, but it signals that the Java language designers consider valueOf() the better choice going forward. Updating old code to use valueOf() is a low-priority refactoring task.

Comparing the four methods side by side

MethodInputOutput TypeHandles PrefixesBest For
Integer.parseInt()Stringprimitive intNo (unless radix specified)Speed-critical code, primitive values
Integer.valueOf()StringInteger objectNo (unless radix specified)Collections, methods expecting objects
Integer.decode()String with optional prefixInteger objectYes (0x, 0, none)Parsing prefixed number strings
new Integer()StringInteger objectNoLegacy code only (deprecated)

Frequently Asked Questions

What is the difference between parseInt and valueOf?

parseInt() returns a primitive int; valueOf() returns an Integer object. If you need to store the value in a collection or pass it to a method expecting an object, use valueOf(). For simple arithmetic or comparisons, parseInt() is faster and uses less memory. Both throw the same exception for invalid input.

Why does my code throw NumberFormatException?

This happens when the string contains characters that are not valid digits for the base you specified. Common causes are spaces within the string (leading or trailing spaces are fine), letters in a decimal string, or the wrong radix for the number format. Check the string content and ensure it matches the radix you passed to the method.

Can I convert a string with a decimal point to an integer?

No, parseInt() and valueOf() reject strings like "42.5" because they only handle whole numbers. If you need to convert a decimal string, use Double.parseDouble() first, then cast to int: int result = (int) Double.parseDouble("42.5"). This truncates the decimal part.

How do I convert a hexadecimal string like "FF" to an integer?

Use Integer.parseInt("FF", 16) to specify radix 16, which returns 255. Alternatively, use Integer.decode("0xFF") if the string includes the "0x" prefix. The radix parameter approach is more flexible because it works whether or not the prefix is present.

Is it safe to convert user input directly without error handling?

No. User input should always be wrapped in a try-catch block because you cannot may provide it will be a valid number. If the conversion fails and you do not catch the exception, your program will crash. Always handle NumberFormatException when the input source is not under your control.