../courses.php
Java
JAVA103
3
Bad Data In
Java programs must check data before trusting it.
Can programs trust user input?
No. Programs should treat user input as untrusted until it has been checked, cleaned, and converted safely.
Real users do unexpected things.
They leave fields blank, type words where numbers belong, or send broken data from another system.
Java gives you types, but types do not replace validation.
A program should check input before using it.
Bad data should be handled clearly instead of crashing the program later.
Checking input before using it
public class Main {
public static void main(String[] args) {
String ageText = "20";
if (ageText.matches("[0-9]+")) {
int age = Integer.parseInt(ageText);
System.out.println("Age: " + age);
} else {
System.out.println("Age must be a number.");
}
}
}
ageText starts as text.
matches("[0-9]+") checks that the text contains only digits.
Integer.parseInt converts the text into an integer.
The conversion happens only after the check passes.
The error path explains what went wrong.
Input
Most software receives data from outside itself.
Validation
Validation protects the rest of the program.
Conversion
Text must often be converted into numbers or dates.
Failure
Bad input should fail clearly and safely.
Trusting input too soon
int age = Integer.parseInt(ageText);
Checking before converting
if (ageText.matches("[0-9]+")) {
int age = Integer.parseInt(ageText);
}
Ask ChatGPT: "Does this Java code validate input before converting or using it?"
Create a String variable that holds age text.
Check whether the text contains only digits.
Convert it to an int only after the check passes.
Show an error message when the check fails.
Explain why input should not be trusted automatically.
Parsing input before checking it.
Assuming users type the right thing.
Confusing Java types with input validation.
Crashing instead of showing a clear error.
Testing only perfect input.
Check simple user input before converting it in Java.
Login - Jit4All
Login
Welcome back to Jit4All