Back to Blog
Java

Java String to int: Parse and Handle Errors

java string to int: Convert a Java String to int using parseInt and valueOf, handle invalid input, and avoid common pitfalls with practical examples.

JavaString parsingNumberFormatExceptionIntegertype conversion
Illustration of converting a string to an integer in Java with error handling.

java string to int requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

When you need to turn a String into an int in Java, the standard answer is Integer.parseInt(String) or Integer.valueOf(String). Both are static methods on the Integer class, but they differ in return type and, in some edge cases, in how they behave. The most direct form is int number = Integer.parseInt("42");. That line works for well-formed numeric strings, but production code rarely receives clean input. The real work is deciding how to handle strings that are not valid integers, and which method fits the situation.

The Two Standard Conversion Methods

Integer.parseInt(String s) returns a primitive int. Integer.valueOf(String s) returns an Integer object. For most conversions, the choice matters only if you need an object for generics or collections. For example, List<Integer> requires Integer, so valueOf is convenient. Otherwise, parseInt avoids unnecessary boxing.

int primitive = Integer.parseInt("123"); Integer boxed = Integer.valueOf("123");

Both methods throw NumberFormatException if the string cannot be parsed as a signed decimal integer. The exception message includes the offending input, which helps during debugging but is not a substitute for validation.

Handling NumberFormatException

The most common failure mode is passing a string that is not a valid integer. This includes empty strings, strings with letters, or values outside the int range. The exception is unchecked, so the compiler will not force you to catch it, but ignoring it crashes the program.

public static int parseOrDefault(String input, int fallback) { try { return Integer.parseInt(input); } catch (NumberFormatException e) { return fallback; } }

This pattern is simple and effective. The fallback value can be a default like 0 or a sentinel that indicates a missing value. If the caller needs to know whether parsing succeeded, returning a sentinel may be ambiguous. In that case, consider returning an OptionalInt.

Parsing with a Custom Radix

Both methods have overloads that accept a radix. Integer.parseInt(String s, int radix) parses the string as a number in that base. This is useful for hexadecimal, octal, or binary input.

int hex = Integer.parseInt("FF", 16); // 255 int binary = Integer.parseInt("1010", 2); // 10

The radix must be between Character.MIN_RADIX (2) and Character.MAX_RADIX (36). Otherwise, the method throws NumberFormatException. The string can still contain a leading minus sign, so Integer.parseInt("-FF", 16) returns -255.

Handling Whitespace and Signs

parseInt does not trim whitespace. A string like " 42" or "42 " throws NumberFormatException. The same applies to tabs and newlines. You must trim the input before parsing if your data may contain surrounding spaces.

String input = " 42 "; int value = Integer.parseInt(input.trim());

Signs are allowed. A leading + or - is accepted, but only one sign character. Strings like "+-42" or "--42" are invalid. The sign must appear before any digits, and there can be no characters after the digits.

Performance Considerations: parseInt vs valueOf

From a performance standpoint, parseInt is slightly cheaper because it returns a primitive and avoids allocating an Integer object. valueOf internally calls parseInt and then boxes the result. In hot loops where you parse many strings, the difference can accumulate, but for typical application code it is negligible. The real performance cost is often the exception itself: constructing and throwing NumberFormatException is expensive compared to a simple conditional check. If you expect many invalid inputs, validate the format before parsing, or use a regex to pre-screen. However, regex validation can be slower than just attempting the parse and catching the exception for the rare invalid case. The right choice depends on your input distribution.

Using OptionalInt for Explicit Missing Values

Java 8 introduced OptionalInt, which is a clean way to represent the result of a parse that might fail. You can combine it with parseInt in a small helper.

import java.util.OptionalInt; public static OptionalInt parseToOptional(String input) { try { return OptionalInt.of(Integer.parseInt(input)); } catch (NumberFormatException e) { return OptionalInt.empty(); } }

This forces the caller to handle the absence of a value explicitly, which reduces the chance of silently using a wrong default. It also avoids the ambiguity of a sentinel like -1 when -1 is a legitimate value.

Common Pitfalls and Maintainability

One recurring mistake is assuming that parseInt handles locale-specific number formats, such as decimal commas or thousands separators. It does not. Only ASCII digits and an optional leading sign are accepted. If your input comes from a locale-aware source, use NumberFormat or DecimalFormat instead.

Another pitfall is ignoring the integer range. Integer.parseInt("2147483648") throws NumberFormatException because the value exceeds Integer.MAX_VALUE. If your domain requires larger numbers, use Long.parseLong or BigInteger.

For maintainability, centralize parsing logic in a utility method rather than scattering try-catch blocks throughout the codebase. This makes error-handling behavior consistent and easier to test. When you need a default value, a method like parseOrDefault is clear. When you need to distinguish "not a number" from "zero", use OptionalInt. The key is to decide early what the failure semantics should be and apply them uniformly.

When to Use Integer.decode

There is a less common method called Integer.decode(String), which handles Java literal syntax, including decimal, hexadecimal (with 0x prefix), octal (with leading zero), and a trailing L (though that is ignored for int). This is useful when you are parsing configuration values that may be written as 0xFF or 010. However, decode does not trim whitespace and still throws NumberFormatException on invalid input. For ordinary decimal strings, parseInt is the more direct choice.

int decoded = Integer.decode("0xFF"); // 255

If you need to support both decimal and prefixed formats, decode saves you from writing your own prefix detection. But be aware that it treats a leading zero as octal, which can surprise developers who expect decimal. For example, Integer.decode("010") returns 8, not 10. Use it only when the Java literal syntax is intentional.

java string to int: Practical Usage and Code Examples | RYUSLOG DEV