Day 6: Understanding Java’s if, else if, and else Statements

Published: (December 24, 2025 at 12:43 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

What Are Conditional Statements?

Conditional statements in Java are used to control the flow of a program only when a condition is true. This is very useful when a program needs to behave differently for different inputs.

The if Statement

The if statement checks a condition inside parentheses.

  • If the condition is true, the code inside the block runs.
  • If the condition is false, the code is skipped.

Example

int score = 60;

if (score >= 50) {
    System.out.println("You passed the exam!");
}

The else if Statement

The else if statement is used to check another condition when the first if condition is false.

Example

int score = 75;

if (score >= 90) {
    System.out.println("Excellent!");
} else if (score >= 50) {
    System.out.println("You passed.");
}

The else Statement

The else statement runs when none of the above conditions are true.

Example

int score = 40;

if (score >= 90) {
    System.out.println("Excellent!");
} else if (score >= 50) {
    System.out.println("You passed.");
} else {
    System.out.println("You failed.");
}

Simple Rule to Remember

  • if → checks the first condition
  • else if → checks additional conditions
  • else → runs when all conditions are false

Only one block executes in an if–else if–else structure.

Task Assigned for the Day

Set the account balance as 5000.

  • If the balance is below 5000, display: "Withdrawal successfully"
  • If the balance is more than 5000, display: "Withdrawal Failed"

Sample Code

package demo;

public class Sample {
    public static void main(String[] args) {
        int balance = 4500;

        if (balance > 5000) {
            System.out.println("Withdrawal Failed!");
        } else {
            System.out.println("Withdrawal successfull");
        }
    }
}

Explanation

  • balance is currently set to 4500.
  • Since the balance is less than 5000, the program prints “Withdrawal successfull”.
  • If the balance were greater than 5000, it would print “Withdrawal Failed!”.
Back to Blog

Related posts

Read more »

🍽️ APIs Explained Like You're 5

The Restaurant Analogy Imagine you're at a restaurant. You don't walk into the kitchen to cook your own food. You → Waiter → Kitchen - You tell the waiter what...