How do I convert a String to an int in Java?

To convert a String to an int in Java, use the Integer.parseInt() method. Here’s how to do it, including handling common edge cases and exceptions:

1. Basic Conversion

String numberStr = "123";
int number = Integer.parseInt(numberStr); // Result: 123 (primitive int)

2. Handling Invalid Input

Use a try-catch block to avoid NumberFormatException for invalid strings:

String input = "12a3";
try {
    int num = Integer.parseInt(input);
    System.out.println("Valid integer: " + num);
} catch (NumberFormatException e) {
    System.out.println("Invalid input: " + input);
}

3. Trim Whitespace

Remove leading/trailing whitespace before parsing:

String input = "  456  ";
int num = Integer.parseInt(input.trim()); // Trim whitespace first

4. Convert to Integer Object

Use Integer.valueOf() to get an Integer object (instead of primitive int):

String input = "789";
Integer number = Integer.valueOf(input); // Returns Integer object

5. Specify Number Base (Radix)

Parse numbers in different bases (e.g., binary, hexadecimal):

String binaryStr = "1010"; // Binary (base 2)
int decimal = Integer.parseInt(binaryStr, 2); // Result: 10

String hexStr = "1A"; // Hexadecimal (base 16)
int hexValue = Integer.parseInt(hexStr, 16); // Result: 26

Common Errors & Solutions

CaseExampleSolution
Null inputString s = nullCheck for null: if (s != null) { ... }
Empty string""Validate input before parsing
Non-numeric characters"123a"Use try-catch or regex validation
Overflow"2147483648"Use Long.parseLong() for large values

Alternative: Apache Commons

For more flexible parsing (returns null for invalid input):

import org.apache.commons.lang3.math.NumberUtils;

String input = "invalid";
Integer number = NumberUtils.toInt(input); // Returns 0 if parsing fails
Integer safeNumber = NumberUtils.toInt(input, -1); // Returns -1 on failure

Summary

  • Use Integer.parseInt() for standard cases (throws NumberFormatException).
  • Trim whitespace with .trim() if needed.
  • Handle exceptions for invalid input.
  • Use radix for non-decimal numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *