Previous Next

Java if...else Statement

If-Else statements are a component of conditional statements.

There are four types of conditional statements in Java:

If Statement

The if statement is used to run a block of code when a specified condition is true.

Syntax:

if (condition){
  // block of code to be executed if the condition is true
}

Example:

public class Main {
  public static void main(String[] args){
    if (10 > 5){
      System.out.println("10 is greater than 5");
    }
  }
}

Output:

10 is greater than 5

If...else statement

The If...else statement is employed to run a block of code when a given condition is true and an alternative block of code when the condition is not true.

Syntax:

if (condition){
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}

Example:

 public class Main {
  public static void main(String[] args){
    int x = 10;
    if (x > 5) {
      System.out.println("x is greater than 5");
    } else {
      System.out.println("x is not greater than 5");
    }
  }
}

Output:

x is greater than 5

if…elif…else Statement

Java's if-elif-else statement runs a block of code between multiple options.

Syntax:

if (condition){
  // block of code to be executed if condition1 is true
} else if (condition2){
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}

Example:

public classMain {
  public static void main(String[] args) {
    int x = 10;
    if (x > 15) {
      System.out.println("x is greater than 15");
    } else if (x > 10) {
      System.out.println("x is greater than 10 but less than or equal to 15");
    } else {
      System.out.println("x is equal to 10");
    }
  }
}

Output:

x is equal to 10
Previous Next