Input Validation
in Java
Learn to validate assumptions and handle invalid input formats to write robust, crash-resistant Java programs.
What Is Input Validation?
Input validation is the process of checking whether data provided by a user (or another system) meets the expected format, type, and range before your program tries to use it.
Without validation, a single unexpected input, like the word "hello" where a number is expected, can crash your entire program with an unhandled exception.
Why Does It Matter?
The Validation Flow
Two Core Strategies
hasNext() vs try-catch
| hasNextInt() / LBYL | try-catch / EAFP | |
|---|---|---|
| When to use | Reading from Scanner | Parsing String values |
| Checks type | ✓ Before reading | ★ After attempting |
| Consumes input | No (peek only) | N/A (already a String) |
| Exception thrown | None (prevented) | Caught and handled |
| Code readability | Explicit and clear | Concise for parsing |
The Validation Loop Pattern
The standard approach wraps input reading in a while loop that repeats until valid data is received.
How to Apply It
Example 1: Type Validation
Example 2: Range Validation
Example 3: try-catch Parsing
Full try-catch Loop
Validating String Format
Sometimes the input is a String and you need to check its format: not empty, correct length, matching a pattern, etc.
Common Mistakes
Validation Techniques Summary
| Technique | Use Case | Key Method |
|---|---|---|
| Type check (LBYL) | Scanner integer input | hasNextInt() |
| Type check (LBYL) | Scanner double input | hasNextDouble() |
| Parse (EAFP) | String to int | Integer.parseInt() |
| Range check | Value within bounds | if (x >= min && x <= max) |
| Format check | String pattern | String.matches(regex) |
| Null/empty check | Avoid NullPointerException | str != null && !str.isEmpty() |
Question 1 of 5
What does hasNextInt() return when the next token in the Scanner buffer is the String "hello"?
Question 2 of 5
Consider this code fragment:
while (!sc.hasNextInt()) {
System.out.println("Invalid!");
}
int x = sc.nextInt();
If the user types "abc", what happens?
Question 3 of 5
Which exception does Integer.parseInt("12.5") throw?
Question 4 of 5
After calling sc.nextInt(), the newline character remains in the buffer. What is the best practice before calling sc.nextLine()?
Question 5 of 5
Consider the following validation code:
try {
int age = Integer.parseInt(input);
if (age < 0 || age > 150) {
System.out.println("Out of range");
}
} catch (Exception e) {
System.out.println("Not a number");
}
Which statement best describes a problem with this code?