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

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

  1. We start with a score variable set to 85. This will determine which condition path we take.
  2. We start with a score variable set to 85. This will determine which condition path we take.
  3. First condition: score >= 90? Since 85 >= 90 is false, we skip this block.
  4. Second condition: score >= 80? Since 85 >= 80 is true, we enter this block!
  5. Executing the matched condition: grade = "B" and print "Good job!"
  6. Executing the matched condition: grade = "B" and print "Good job!"
  7. After if-else ladder, we continue with the rest of the code . We won't look in othe if conditions.
  8. We will print the statement

Common mistakes

Best practices

·

More in Conditional Statements