DEV Community

Karthick Narayanan
Karthick Narayanan

Posted on

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

What Are Conditional Statements?

Conditional statements in Java are used to control the flow of a program.
They allow Java to execute certain code 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!");
}
Enter fullscreen mode Exit fullscreen mode

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.");
}
Enter fullscreen mode Exit fullscreen mode

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.");
}
Enter fullscreen mode Exit fullscreen mode

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

  1. Set the account balance as 5000
  2. If the balance is below 5000, display: "Withdrawal successfully"
  3. If the balance is more than 5000, display: "Withdrawal Failed"
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");
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • balance is currently set to 4500
  • If balance is less than 5000 → Withdrawal successfully
  • If balance is more than 5000 → Withdrawal Failed

Top comments (0)