Java Else Statement

The else statement in Java is used in conjunction with an if statement to execute a block of code when the condition in the if statement is false.

Key Topics

1. Syntax

The syntax for an if...else statement is:

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

2. Example

Example of using if and else:

public class IfElseExample {
    public static void main(String[] args) {
        int number = 3;
        if (number % 2 == 0) {
            System.out.println("The number is even.");
        } else {
            System.out.println("The number is odd.");
        }
    }
}

Key Takeaways

  • The else block executes when the if condition is false.
  • Using else provides an alternative path for code execution.
  • if...else statements help in decision-making processes in your program.