Task 4 of 8 · 0 solved · 8 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

2.1 Selection — if / else

Lesson

if / else

else gives an alternative that runs when the condition is false. Exactly one of the two branches runs — never both, never neither.


Worked example

int x = -3;
if (x > 0) {
    System.out.println("positive");
} else {
    System.out.println("not positive");
}

x is -3, so x > 0 is false: the else branch runs and it prints not positive.


▶ Try it: run this, then flip x between negative and positive — exactly one of the two lines prints each time.



What does the code above print when x is -3?


What does the same code print when x is 7?


True or false?


Type exactly what this prints:

int x = 4;
if (x % 2 == 0) {
    System.out.println("even");
} else {
    System.out.println("odd");
}

For if (x > 0) ... else, sort each value of x by which branch runs.