01 / 20

Input Validation
in Java

Learn to validate assumptions and handle invalid input formats to write robust, crash-resistant Java programs.

Computer Science Java Input Validation

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?

✕ Crashes
Unvalidated input causes runtime exceptions like InputMismatchException and NumberFormatException.
★ Security
Malicious input can exploit your program. Validation is the first line of defense.
✓ User Experience
Good validation gives clear error messages so users can fix their input immediately.

The Validation Flow

User Input Validate Type? Range? Format? Valid Invalid Process Use the data Re-prompt Show error msg Ask again

Two Core Strategies

LBYL
Look Before You Leap. Check the input before attempting to use it. Use hasNextInt(), String.matches(), range checks.
EAFP
Easier to Ask Forgiveness than Permission. Try to use the input and catch exceptions if it fails. Use try-catch blocks.

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.

1
Prompt the user for input.
2
Check if the input is the correct type and in the valid range.
3
If invalid: display an error message, consume the bad input, and loop back to step 1.
4
If valid: read and store the value, then exit the loop.

How to Apply It

1
Identify your assumptions: What type should the input be? What range is valid?
2
Choose your strategy: Use hasNextInt() for Scanner, try-catch for String parsing.
3
Write the validation loop: A while loop that re-prompts on failure.
4
Clear bad input: Call scanner.next() or scanner.nextLine() to discard the invalid token.
5
Give clear feedback: Tell the user exactly what went wrong and what is expected.

Example 1: Type Validation

JAVA: Validating integer input with hasNextInt()
Scanner sc = new Scanner(System.in); System.out.print("Enter your age: "); while (!sc.hasNextInt()) { System.out.println("That's not a number. Try again:"); sc.next(); // discard the invalid token } int age = sc.nextInt();

Example 2: Range Validation

JAVA: Ensuring age is between 0 and 150
int age = -1; while (age < 0 || age > 150) { System.out.print("Enter age (0-150): "); while (!sc.hasNextInt()) { System.out.println("Not a number. Try again:"); sc.next(); } age = sc.nextInt(); if (age < 0 || age > 150) { System.out.println("Age must be 0-150."); } }

Example 3: try-catch Parsing

JAVA: Parsing a String to int with exception handling
String input = "42abc"; try { int num = Integer.parseInt(input); System.out.println("Parsed: " + num); } catch (NumberFormatException e) { System.out.println("Invalid format: " + input); }

Full try-catch Loop

JAVA: Validation loop using try-catch
Scanner sc = new Scanner(System.in); int num = 0; boolean valid = false; while (!valid) { System.out.print("Enter a number: "); try { num = Integer.parseInt(sc.nextLine()); valid = true; } catch (NumberFormatException e) { System.out.println("Invalid! Enter an integer."); } }

Validating String Format

Sometimes the input is a String and you need to check its format: not empty, correct length, matching a pattern, etc.

JAVA: Validating a yes/no response
String response; while (true) { System.out.print("Enter yes or no: "); response = sc.nextLine().trim(); if (response.equalsIgnoreCase("yes") || response.equalsIgnoreCase("no")) { break; } System.out.println("Please type 'yes' or 'no'."); }

Common Mistakes

✕ Forgetting to Clear Bad Input
Not calling next() after hasNextInt() returns false creates an infinite loop: the bad token stays in the buffer.
✕ Catching Too Broadly
Using catch (Exception e) instead of the specific type hides real bugs. Catch NumberFormatException or InputMismatchException specifically.
✕ Mixing nextInt() and nextLine()
nextInt() leaves the newline in the buffer. A following nextLine() reads an empty string. Use nextLine() + parseInt() instead.

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

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

Which statement best describes a problem with this code?