How do I fix cannot convert string to int in Java?
What causes this error
In Java, Integer.parseInt() and similar methods throw NumberFormatException if the string cannot be parsed as an integer. This occurs if the string contains non-numeric characters, is empty, or represents a number outside the int range (e.g., "2147483648").
Common sources include user input, reading from files, or parsing JSON/XML where values might be empty or contain decimals. Even leading/trailing spaces can cause it if not trimmed.
How to fix it
First, validate the string before parsing. Use a regular expression like "-?\\d+" to check if it's a valid integer. If it might contain decimals, use Double.parseDouble() instead. If the string could be empty, provide a default value.
Wrap the parsing in a try-catch block to handle NumberFormatException gracefully. You can log the error, show a message to the user, or use a fallback value. For large numbers, use Long.parseLong() or BigInteger.
If the string comes from user input, trim it first with .trim() to remove accidental spaces. If it contains commas (e.g., "1,000"), remove them before parsing.
- Use trim() to remove leading/trailing whitespace.
- Validate with a regex or a library like Apache Commons Lang's StringUtils.isNumeric().
- Use try-catch to handle NumberFormatException.
- For decimals, use Double.parseDouble() or BigDecimal.
- For very large integers, use Long.parseLong() or BigInteger.
Examples
If you have String input = "123 "; int num = Integer.parseInt(input.trim()); works. If input = "12.5", you can use double num = Double.parseDouble(input);. If input = "abc", you must catch the exception or validate first.
When reading from a file, check for empty lines or headers. For example, skip lines that don't match the expected format. If using a Scanner, you can use hasNextInt() to check before calling nextInt().
Common mistakes
- Not trimming the string before parsing, leading to errors from whitespace.
- Assuming the string is always a valid integer without validation or exception handling.
- Using Integer.parseInt() for numbers that might have decimal points or be too large.
