JAVA CONDITIONS

Java else statement

else lets you run an alternative code block when the preceding if statement's condition is false.

When does the else block run?

if and else provide two possible paths. If the condition returns true, the first block runs. If it returns false, the first block is skipped and the else block runs. Only one of these blocks runs each time the condition is checked.

else statement syntax

if (sąlyga) {
    // Runs when the condition is true
} else {
    // Runs when the condition is false
}
  1. if parentheses contain the condition Java checks.
  2. If the condition is true, the first block inside braces runs.
  3. If the condition is false, the first block is skipped and the else block.
  4. Java selects only one of these two paths each time it checks the condition.
This syntax template produces no console output.

The word sąlyga and the comments simply show where to put the actual condition and statements to execute.

else has no condition of its own.

It runs automatically when the associated if condition is false.

An everyday decision example

The program decides whether Jonas needs to take an umbrella:

boolean jonuiReikiaSkecio = false;

if (jonuiReikiaSkecio) {
    System.out.println("Jonai, pasiimk skėtį!");
} else {
    System.out.println("Jonai, šiandien skėčio nereikia!");
}
Console output

Jonai, šiandien skėčio nereikia!

  1. The variable jonuiReikiaSkecio is like a box that can hold only the answer “yes” or “no”.
  2. Meaning false here means “no, Jonas does not need an umbrella”.
  3. if checks this value. Since it is not true, the first block is skipped.
  4. Java moves to the else block and displays in the console that Jonas does not need an umbrella.
What would change with true?

Java would run the first block and display Jonai, pasiimk skėtį!. else block would then be skipped.

Important else rules

  • else comes immediately after the associated if block.
  • else cannot be used alone without a preceding if.
  • Each if can have only one final else block.
  • To check another condition, use an else if statement.