Task 2 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 — the if statement

Lesson

Selection: making decisions

So far every line ran, always. An if statement lets a program choose — run some code only when a condition holds. Module 2 (Selection & Iteration) starts here.


The if statement

if (condition) { ... } runs the code in the braces only when the condition (a boolean) is true. If it is false, the body is skipped. Code after the if runs either way.


Worked example

int x = 5;
if (x > 0) {
    System.out.println("positive");
}
System.out.println("done");

x is 5, so x > 0 is true: it prints positive, then done.


▶ Try it: run this, then change x to a negative number and run again — the positive line disappears, but done always prints.



What does this print when x is 5?

if (x > 0) {
    System.out.println("positive");
}
System.out.println("done");

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


True or false?


Type exactly what this prints:

int x = 2;
if (x > 0) {
    System.out.println("yes");
}

Assemble a valid if statement that prints hi when x > 0.