Quick Answer

Safely convert strings to integers.

Understanding the Issue

NumberFormatException occurs when parsing invalid numeric strings, requiring proper validation and error handling.

The Problem

This code demonstrates the issue:

Java Error
String input = "123a";
int num = Integer.parseInt(input); // Throws

The Solution

Here's the corrected code:

Java Fixed
// Solution 1: Try-catch block
try {
    int num = Integer.parseInt(input);
} catch (NumberFormatException e) {
    num = 0; // Default value
}

// Solution 2: Pre-validation
if (input.matches("-?\d+")) {
    int num = Integer.parseInt(input);
}

// Solution 3: Scanner class
Scanner sc = new Scanner(input);
if (sc.hasNextInt()) {
    int num = sc.nextInt();
}

// Solution 4: NumberUtils (Apache Commons)
// int num = NumberUtils.toInt(input, 0);

Key Takeaways

Always validate string format before numeric conversion.