Module 4: Decision Making
Input Validation with Conditionals
Use conditions to reject bad input and accept only values that make sense for your program.
Author
Java Learner Editorial Team
Reviewer
Technical review by Java Learner
Last reviewed
2026-04-16
Java version
Java 25 LTS
Learning goals
- Check whether user input is inside an allowed range
- Print helpful feedback for invalid input
- Treat validation as part of normal program design
Why this matters: Real programs should not silently accept impossible or confusing values. Validation protects the rest of your logic.
Common beginner checks: Age cannot be negative, a score should stay between 0 and 100, and menu choices should be limited to known options.
Helpful feedback beats vague feedback: Tell the user what was wrong and what the allowed input should be.
Validation is not an extra: It is part of writing reliable code, even in small beginner programs.
Runnable examples
Validate a score range
public class Main {
public static void main(String[] args) {
int score = 120;
if (score < 0 || score > 100) {
System.out.println("Score must be between 0 and 100.");
} else {
System.out.println("Score accepted.");
}
}
}Expected output
Score must be between 0 and 100.
Validate an age
public class Main {
public static void main(String[] args) {
int age = -2;
if (age < 0) {
System.out.println("Age cannot be negative.");
} else {
System.out.println("Age accepted.");
}
}
}Expected output
Age cannot be negative.
Common mistakes
Writing validation after the program already uses the bad value
Validate input early, before the rest of the logic depends on it.
Mini exercise
Write a condition that accepts only menu choices from 1 to 4.
Summary
- Validation keeps your program trustworthy.
- Early checks prevent confusing later bugs.
Next step
The next rewrite wave should add loops, methods, arrays, and objects in the same style.
Sources used