How to Convert a String to an int in Java

Use Integer.parseInt(s) to convert a String to a primitive int, or Integer.valueOf(s) for a boxed Integer. Both throw NumberFormatException if the string is not a valid integer.

parseInt — primitive int

String s = "42";
int n = Integer.parseInt(s); // 42

int negative = Integer.parseInt("-17"); // -17

valueOf — boxed Integer

String s = "42";
Integer n = Integer.valueOf(s); // Integer(42)
// Unboxes automatically when used as int:

Use valueOf when you need an Integer object (e.g. for a List<Integer>). Use parseInt for a primitive. In practice, they are interchangeable for most code due to auto-unboxing.

Handling NumberFormatException

String input = "abc";
try {
    int n = Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Not a valid integer: " + input);
}

Safe conversion without exception

public static OptionalInt tryParseInt(String s) {
    try {
        return OptionalInt.of(Integer.parseInt(s));
    } catch (NumberFormatException e) {
        return OptionalInt.empty();
    }
}

// Usage:
OptionalInt result = tryParseInt(userInput);
int value = result.orElse(0); // default to 0 if invalid

Handling null input

String s = null;
Integer.parseInt(s);  // NumberFormatException ("null")
Integer.valueOf(s);   // NumberFormatException

Check for null before parsing if the string might be absent:

if (s != null && !s.isBlank()) {
    int n = Integer.parseInt(s.trim());
}

Parse with a different radix

int decimal = Integer.parseInt("2a", 16);  // 42 (hex)
int binary  = Integer.parseInt("101010", 2); // 42 (binary)
int octal   = Integer.parseInt("52", 8);    // 42 (octal)

Parsing larger numbers

long big = Long.parseLong("9999999999");    // for values beyond int range
double d = Double.parseDouble("3.14");      // for floating point
BigDecimal bd = new BigDecimal("1.005");    // for exact decimal values

Common mistake: not trimming whitespace

String fromUser = "  42  ";
Integer.parseInt(fromUser);        // NumberFormatException — leading/trailing spaces
Integer.parseInt(fromUser.trim()); // 42 — correct