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.
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.
if (condition) { ... }
boolean
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.
x > 0
positive
done
▶ Try it: run this, then change x to a negative number and run again — the positive line disappears, but done always prints.
x
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.
hi