Notifications
Clear all
Topic starter 01/08/2025 11:55 pm
🤖 What is an if-then-else
statement in Java?
In Java, if-then-else
statements allow your program to make decisions. It’s like giving your code a brain to choose different paths based on conditions.
📦 Basic Structure
if (condition) {
// Code runs if condition is true
} else {
// Code runs if condition is false
}
🧠 How it works
- The
condition
inside the parentheses must evaluate to a boolean (true
orfalse
) - If
true
, the code block underif
runs - If
false
, theelse
block runs instead
🔍 Example
int score = 85;
if (score >= 90) {
System.out.println("Excellent!");
} else {
System.out.println("Keep trying!");
}
In this case:
- If
score
is 90 or more, it prints “Excellent!” - Otherwise, it prints “Keep trying!”
🎯 Adding else if
for more choices
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 75) {
System.out.println("Good job!");
} else {
System.out.println("Keep trying!");
}
Now there are three possible outcomes based on the value of score
.