NumberFormatException in Java
Fast recall
Quick revision
Core answer
NumberFormatException occurs when a string cannot be parsed in the format required by a numeric method such as Integer.parseInt. Examples include an empty string, "12.5" passed to parseInt, or a value outside the int range. At an input boundary, trim only if the contract permits it, call the correct parser, catch NumberFormatException, and return a clear validation error or another result that represents invalid input.Interview-ready guide
Interview answer
NumberFormatException means a numeric parsing method received text that is not valid for its target type. For example, Integer.parseInt("12.5") fails because an integer parser does not accept a decimal point, and a very large sequence of digits can fail because it is outside the int range. I handle it where the text enters the system: apply the documented trimming rule, call the correct parser, catch this specific exception, and return a clear validation result. I do not depend only on a regular expression, because the parser also enforces range and exact format rules.
NumberFormatException in Java
Direct Answer
NumberFormatException occurs when a string cannot be parsed in the format required by a numeric method such as Integer.parseInt. Examples include an empty string, "12.5" passed to parseInt, or a value outside the int range. At an input boundary, trim only if the contract permits it, call the correct parser, catch NumberFormatException, and return a clear validation error or another result that represents invalid input.
Code Example
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@GetMapping("/{orderId}")
public ResponseEntity<?> getOrder(@PathVariable String orderId) {
try {
Long id = Long.parseLong(orderId);
var order = orderService.findById(id);
return ResponseEntity.ok(order);
} catch (NumberFormatException e) {
// Return 400 Bad Request with helpful message
return ResponseEntity
.badRequest()
.body(Map.of("error", "Order ID must be a valid number"));
}
}
// Alternative: validation before parsing
public Optional<Integer> parseQuantity(String input) {
if (input == null || !input.matches("\\d+")) {
return Optional.empty(); // invalid format
}
return Optional.of(Integer.parseInt(input)); // safe now
}
}
Common Mistakes & Pitfalls
- Letting exceptions propagate: Freshers allow NumberFormatException to bubble up to the framework, resulting in generic 500 errors shown to users. Always catch it at the controller layer and return a proper 400 with a meaningful message.
- Not trimming whitespace: Calling parseInt on " 123 " (with spaces) throws NumberFormatException. Always trim input strings before parsing.
- Parsing without validation: Calling parseInt on every user input without checking format first makes your API fragile. Validate or wrap in try-catch to handle bad input gracefully.
Check your understanding
Answer these without looking back at the article.
- What is the difference between Integer.parseInt() and Integer.valueOf()?
- How does Spring Boot handle type conversion for request parameters?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.