The three main ways to convert a string to an integer in Java

Java gives you three straightforward methods to turn a string into an integer: Integer.parseInt(), Integer.valueOf(), and the Integer constructor. The first two are what you'll use in almost all situations. Integer.parseInt() returns a primitive int, while Integer.valueOf() returns an Integer object that wraps the int value. The constructor method works but is considered outdated in modern Java code.

The choice between parseInt() and valueOf() matters only if your code needs to distinguish between a primitive int and an Integer object. For most everyday programming, parseInt() is simpler and slightly faster because it doesn't create an object wrapper. If you're storing the result in a collection or passing it to a method that expects an Integer object, valueOf() is the natural choice.

Key Takeaways

  • Integer.parseInt() converts a string to a primitive int and is the most common choice for basic conversion tasks.
  • Integer.valueOf() converts a string to an Integer object and is useful when you need an object rather than a primitive value.
  • Both methods throw a NumberFormatException if the string contains non-numeric characters or is empty, so you should handle this error in production code.
  • The parseInt() method accepts an optional second parameter to specify the number base (radix), allowing conversion from binary, hexadecimal, or other bases.
  • Null strings and whitespace-only strings cause exceptions, so validate your input before conversion.

Using Integer.parseInt() for basic string-to-int conversion

Integer.parseInt() is the standard tool for converting a string containing digits into a primitive int. The syntax is straightforward: you pass the string as an argument, and it returns the integer value.

Here's a working example:

String text = "42"; int number = Integer.parseInt(text); System.out.println(number); // outputs: 42

The method reads the entire string and converts it to its numeric equivalent. If the string is "123", you get the integer 123. If the string contains spaces at the beginning or end, parseInt() ignores them automatically. A string like " 456 " converts without error.

However, if the string contains any non-numeric characters in the middle, or if it's empty, parseInt() throws a NumberFormatException. The string "12a34" will crash your program unless you catch the exception. This is why production code almost always wraps parseInt() in a try-catch block.

Handling errors when conversion fails

When parseInt() encounters a string it cannot convert, it throws a NumberFormatException. This happens with strings like "abc", "12.5", or an empty string "". Your code stops running at that point unless you catch the exception.

The standard pattern is to wrap the conversion in a try-catch block:

String userInput = "not a number"; try {   int number = Integer.parseInt(userInput);   System.out.println("Converted: " + number); } catch (NumberFormatException e) {   System.out.println("That's not a valid number"); }

In this pattern, if the conversion fails, the catch block runs instead of crashing. You can then handle the error gracefully — display a message to the user, use a default value, or log the problem. This approach is essential when converting user input, data from files, or any string you don't fully control.

Converting strings in different number bases with parseInt()

Integer.parseInt() accepts a second parameter called the radix, which specifies the number base. This lets you convert strings representing binary, hexadecimal, octal, or any base from 2 to 36.

Common examples include:

int binary = Integer.parseInt("1010", 2); // converts to 10 int hex = Integer.parseInt("FF", 16); // converts to 255 int octal = Integer.parseInt("77", 8); // converts to 63

The first parameter is always the string, and the second is the base. When you specify base 2, the method expects only the digits 0 and 1. For base 16 (hexadecimal), it accepts 0–9 and A–F (case-insensitive). If you pass a digit that doesn't exist in that base — like "2" in binary — you get a NumberFormatException.

This feature is useful when parsing configuration files, working with network protocols, or handling data from systems that use non-decimal bases. Most everyday code uses base 10 (the default), so you won't need the radix parameter often.

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. The syntax is identical:

String text = "42"; Integer number = Integer.valueOf(text); System.out.println(number); // outputs: 42

The difference matters when your code works with collections or methods that expect objects. If you're adding numbers to an ArrayList or HashMap, valueOf() is the natural choice because those collections store objects, not primitives. Java will automatically convert between Integer objects and primitive ints in most situations, but valueOf() makes the intent clear.

Integer.valueOf() also accepts a radix parameter, just like parseInt(): Integer.valueOf("FF", 16) converts the hexadecimal string to an Integer object with the value 255. It throws the same NumberFormatException for invalid input, so you still need try-catch blocks in production code.

The difference between parseInt() and valueOf()

Both methods convert a string to an integer value, but they return different types. parseInt() returns a primitive int — a straightforward numeric value with no object overhead. valueOf() returns an Integer object that wraps the int value inside it.

In practice, this distinction rarely matters. Modern Java automatically converts between primitive ints and Integer objects in most contexts, a feature called autoboxing. You can assign the result of valueOf() to an int variable, and Java handles the conversion invisibly. You can pass a primitive int where an Integer object is expected, and it works.

The real difference shows up in performance-critical code or when you're explicitly checking types. parseInt() is marginally faster because it skips the object creation step. If you're converting millions of strings in a loop, parseInt() uses less memory. For typical process code, the difference is negligible. Choose parseInt() for simplicity, and valueOf() when you explicitly need an object.

Avoiding the Integer constructor method

Older Java code sometimes uses the Integer constructor to convert strings: new Integer("42"). This works but is now considered outdated. The Java documentation marks this constructor as deprecated, meaning it may be removed in future versions of Java.

The constructor does exactly what valueOf() does — it returns an Integer object — but without the performance optimizations that valueOf() includes. Modern code should use valueOf() instead. If you encounter the constructor in existing code, you can safely replace it with valueOf() without changing how the program behaves.

Frequently Asked Questions

What happens if I try to convert a string with decimal points like "12.5"?

Integer.parseInt() throws a NumberFormatException because it only recognizes whole numbers. If you need to convert "12.5" to a number, you must first use Double.parseDouble() to get 12.5, then cast it to an int if you need an integer. Casting 12.5 to int gives you 12 — the decimal part is discarded.

Can I convert a string with leading zeros like "007"?

Yes. Integer.parseInt("007") returns 7. Leading zeros are ignored. The only exception is if you specify base 8 (octal) as the radix — then "007" is interpreted as octal 7, which is still decimal 7, but "010" would be octal 10, which equals decimal 8.

What if the string is null?

Passing null to parseInt() or valueOf() throws a NullPointerException. Always check that your string is not null before attempting conversion. A straightforward null check — if (text != null) — prevents this error.

How do I convert a string with a plus or minus sign like "+42" or "-42"?

Both parseInt() and valueOf() handle signed numbers correctly. Integer.parseInt("+42") returns 42, and Integer.parseInt("-42") returns -42. The plus or minus sign is recognized and processed automatically.

Is there a way to convert without throwing an exception if the string is invalid?

The try-catch block is the standard approach, but you can also use Integer.parseInt() with a default value by catching the exception and returning a fallback number. Some developers write a helper method that returns a default value (like 0) if conversion fails, avoiding the need to write try-catch blocks repeatedly.