Utilizor
Contact Us

Java If...Else

Conditional statements.

Examples

The if Statement

Executes code if the condition is true.

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

The else Statement

Executes one block if true, another if false.

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.");
    }
  }
}

The else if Statement

Checking logical conditions.

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

Test Your Knowledge

Java Quiz

No quiz available for this topic yet.