How to Change a String to an Int in Java

Converting a string to an integer is one of the most common tasks in Java development. Whether you're parsing user input, reading data from a file, or processing values from an API response, you'll almost certainly need to handle this conversion at some point. Java gives you several ways to do it — and understanding the differences between them matters more than most tutorials suggest.

Why Strings and Integers Are Stored Differently

Java treats strings and integers as fundamentally different data types. A string like "42" is a sequence of characters stored as a String object. An integer like 42 is a primitive numeric value stored as an int. They look similar to a human reader, but Java cannot do math with a string, compare it numerically, or use it wherever a numeric type is expected.

That's why conversion is necessary — and why Java won't do it automatically.

The Main Methods for Converting String to Int in Java 🔢

Integer.parseInt()

This is the most straightforward and widely used approach:

String numberString = "42"; int result = Integer.parseInt(numberString); 

Integer.parseInt() takes a String argument and returns a primitive int. It's fast, simple, and appropriate for most everyday use cases.

Integer.valueOf()

String numberString = "42"; Integer result = Integer.valueOf(numberString); 

This method also accepts a string but returns an Integer object (the wrapper class) rather than a primitive int. Java can automatically unbox this to a primitive where needed, so in practice the difference is often invisible — but it matters in certain contexts, particularly when working with collections like ArrayList<Integer>.

Integer.decode()

String hexString = "0xFF"; int result = Integer.decode(hexString); 

Integer.decode() is less common but useful when your string represents a number in hexadecimal, octal, or decimal format with a prefix. It handles 0x for hex and 0 for octal automatically.

Comparison at a Glance

MethodReturnsBest For
Integer.parseInt(str)primitive intGeneral use, simple parsing
Integer.valueOf(str)Integer objectCollections, nullable contexts
Integer.decode(str)primitive intHex, octal, or prefixed strings
new Integer(str)Integer objectDeprecated — avoid in modern Java

Handling Errors: The NumberFormatException

This is where many beginners get caught off guard. If the string you're trying to convert isn't a valid integer — say it contains letters, symbols, or is empty — Java will throw a NumberFormatException at runtime.

String bad = "hello"; int result = Integer.parseInt(bad); // Throws NumberFormatException 

To handle this safely, wrap your conversion in a try-catch block:

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

Whether you need that error handling depends heavily on your use case. If you control the data source and know the string will always be a valid integer, skipping the try-catch keeps your code cleaner. If the string comes from user input or an external source, defensive handling is almost always the right instinct.

Radix: Parsing Integers in Different Bases

Integer.parseInt() also accepts a second argument — a radix — that tells Java which number base to use:

String binary = "1010"; int result = Integer.parseInt(binary, 2); // Returns 10 

This is useful when working with binary (2), octal (8), or hexadecimal (16) strings. Without specifying a radix, Java assumes base 10.

Variables That Affect Which Approach You Should Use

Java gives you options because the "right" method depends on several factors:

  • Data source — User input, file data, and API responses all carry different risks of invalid values. Strings you fully control are safer to parse without guards.
  • Type destination — If you're storing the result in a collection, an Integer object (from valueOf()) integrates more naturally than a primitive.
  • Number base — Strings representing hex or binary values need either decode() or parseInt() with a radix argument.
  • Java version — The new Integer(str) constructor was deprecated in Java 9 and removed in later versions. Newer codebases should use parseInt() or valueOf() exclusively.
  • Performance sensitivity — In tight loops processing large datasets, using a primitive int via parseInt() avoids the overhead of object creation that comes with Integer.valueOf().
  • Null handling — Neither parseInt() nor valueOf() handles null strings gracefully. Passing null throws a NumberFormatException, so null checks may need to come first depending on your data pipeline.

When the Same Input Produces Different Outcomes 🎯

Consider two developers writing similar code. One is parsing configuration values from a properties file they fully control — clean integers, no edge cases. parseInt() with no error handling works perfectly. Another is parsing integers from a form field on a web application, where users routinely type text, leave fields blank, or paste formatted numbers like "1,000". Here, even a well-written parseInt() call will fail without preprocessing and exception handling.

The same one-line conversion behaves very differently depending on context. A string like "1,000" will throw a NumberFormatException because parseInt() doesn't recognize comma-formatted numbers — that string would need to be cleaned first (replace(",", "")) before parsing.

What Java Doesn't Do Automatically

Unlike some loosely typed languages, Java won't silently coerce a string to a number. There's no implicit conversion. This strictness is by design — it prevents subtle bugs where a numeric operation produces unexpected results because the input type was assumed rather than verified.

That explicitness is part of why Java remains dominant in enterprise and Android development, where predictable, type-safe behavior matters.

Understanding which method fits your situation — and what can go wrong — depends on the shape of your data, where it comes from, and what happens downstream when the conversion succeeds or fails.