Conditional Statements (if-else)
Learn how to make decisions in your code using conditional statements
Java · beginner · 20 min · 8 steps · free
What you'll learn
- Understand how if-else statements control program flow
- Learn the syntax of if, else if, and else blocks
- Understand that conditions are evaluated in order
- Learn that only one block executes in an if-else ladder
ConditionalDemo.java
public class ConditionalDemo {
public static void main(String[] args) {
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
System.out.println("Excellent!");
} else if (score >= 80) {
grade = "B";
System.out.println("Good job!");
} else if (score >= 70) {
grade = "C";
System.out.println("Average");
} else if (score >= 60) {
grade = "D";
System.out.println("Below average");
} else {
grade = "F";
System.out.println("Failed");
}
System.out.println("Grade: " + grade);
}
}
Step by step
- We start with a score variable set to 85. This will determine which condition path we take.
- We start with a score variable set to 85. This will determine which condition path we take.
- First condition: score >= 90? Since 85 >= 90 is false, we skip this block.
- Second condition: score >= 80? Since 85 >= 80 is true, we enter this block!
- Executing the matched condition: grade = "B" and print "Good job!"
- Executing the matched condition: grade = "B" and print "Good job!"
- After if-else ladder, we continue with the rest of the code . We won't look in othe if conditions.
- We will print the statement
Common mistakes
- Using = instead of == for comparison
- Not understanding that else-if conditions are only checked if previous conditions were false
- Forgetting braces for multi-statement blocks
Best practices
- Always use braces {} even for single statements
- Order conditions from most specific to most general
- Consider using switch statements for multiple exact value comparisons
← Operator Precedence · Switch Statement →
More in Conditional Statements