Lesson 13 +10 XP

Java Conditions (if, else)

Java Conditions (if, else)

Use conditions to run different code depending on whether a test is true or false.

The if statement

Runs a block of code only if the condition is true:

if (20 > 18) {
  System.out.println("20 is greater than 18");
}

The else statement

Runs code when the condition is false:

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}

The else if statement

Checks a new condition when the first one is false:

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

Short hand if else (ternary)

String result = (time < 18) ? "Good day." : "Good evening.";

TL;DR

  • if runs code when the condition is true.
  • else runs code when the condition is false.
  • else if checks another condition.
  • The ternary operator ? : is a short form of if else.