2.3 if statementsChoosing what runs

A one-way if runs its block only when the test is true. If the test is false, Java skips the block and goes on to the next statement. A two-way if-else has two blocks: the if block runs when the test is true, and the else block runs when it's false. Exactly one of the two runs, never both and never neither.
The block is the code between the braces { }. Java doesn't care about indentation, only about braces. If you leave the braces off, only the very next statement belongs to the if. The AP exam writes braces almost everywhere, and you should too.
1int age = 15;2double price = 12.0;3if (age < 13)14{5 price = 8.0;6}7else8{9 price = price - 2.0;210}11if (age >= 65)312{13 price = price / 2;14}15System.out.println(price);
- line 3 false for 15, so the else block runs
- line 9 price becomes 10.0
- line 11 A separate if: checked too, and false
?Wait, what does price = price - 2.0 do?
?Wait, what's a block again?
int x = 8; int y = 0;
if (x > 10)
x = 0;
y = 1;What are x and y afterward? (The indentation is misleading on purpose.)
I thought about it. Show me
What is printed?
int t = 12;
if (t % 2 == 0)
{
t = t / 2;
}
if (t > 5)
{
t -= 4;
}
else
{
t += 10;
}
System.out.println(t);- First if: 12 % 2 is 0, so the test is true and t becomes 6.
- Second if: it's a separate statement, so Java checks it too, using the new value of t. 6 > 5 is true.
Why?
The trap answer uses the old value, 12, or stops after the first if. Each if uses whatever the variables hold at that moment. - The if block runs: t -= 4 makes t 2. The else block is skipped.
Answer: 2
Stuck? Get a hint
- Do the first if completely before you look at the second.
- After the first if, t is 6. Is 6 > 5?
- Only one of the second statement's two blocks runs.
int k = 10;
if (k >= 10)
{
k += 5;
}
if (k < 10)
{
k -= 5;
}
System.out.println(k);- A15
- B5
- C20
- D10
Show the answer
A. k starts at 10. 10 >= 10 is true, so k += 5 makes it 15. The second if is a separate statement, and it uses the current value: 15 < 10 is false, so k stays 15. Choice D is the top trap: it runs both blocks (10 + 5 - 5), but by the time the second test is checked, k is already 15.

On every if question, first ask: is this one statement with else branches, or several separate ifs? Separate ifs are all checked, each with the current values. Draw a line between them on your scratch paper.