Java If ... Else

Java If ... Else Statements

Java supports the usual logical conditions from mathematics. You can use these conditions to perform different actions for different decisions. This is called conditional logic.

Java has the following conditional statements:


1. The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

`if` Statement Example

public class Main {
  public static void main(String[] args) {
    int time = 20;
    if (time < 18) {
      System.out.println("Good day.");
    }
    // Since the condition is false, nothing is printed.
  }
}

2. The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

`if-else` Statement Example

public class Main {
  public static void main(String[] args) {
    int time = 20;
    if (time < 18) {
      System.out.println("Good day.");
    } else {
      System.out.println("Good evening.");
    }
    // Outputs "Good evening."
  }
}

3. The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

`if-else if-else` Example

public class Main {
  public static void main(String[] args) {
    int time = 22;
    if (time < 10) {
      System.out.println("Good morning.");
    } else if (time < 18) {
      System.out.println("Good day.");
    } else {
      System.out.println("Good evening.");
    }
    // Outputs "Good evening."
  }
}

4. Ternary Operator

There is also a short-hand if-else, which is known as the ternary operator because it consists of three operands. It can be used to replace simple if-else blocks.

Syntax: variable = (condition) ? expressionTrue : expressionFalse;

Ternary Operator Example

int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);