AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/2/2-3)
Unit 2 · Topic 2.3
2.3 if Statements
An if statement lets your program choose whether to run a block of code. This topic covers one-way selection (if alone) and two-way selection (if with else), and the brace and semicolon mistakes that make code do something other than what it looks like.
Key terms
ifstatementif-else- one-way selection
- two-way selection
- flow of control
One-way selection
Normally Java runs statements one after another. A selection statement changes that flow of control: some code runs only under certain conditions.
An if statement has a condition in parentheses and a body in braces. The body runs only when the condition is true. When it's false, Java skips the body and carries on after it. This is called one-way selection, because there's only one optional path.
public static double shippingCost(double subtotal)
{
double cost = 6.5;
if (subtotal >= 35.0)
{
cost = 0.0;
}
return cost;
}
Here shipping starts at 6.50 dollars, and the if makes it free only for orders of 35 dollars or more. For a smaller order the condition is false, the body is skipped, and the method returns the starting cost. shippingCost(20.0) returns 6.5, and shippingCost(35.0) returns 0.0.
Two-way selection
An if-else statement has two bodies, and the else has no condition of its own: it simply catches every case the if didn't. Exactly one of them runs: the if body when the condition is true, and the else body when it's false. Never both, and never neither. This is two-way selection.
int temp = 58;
if (temp > 65)
{
System.out.println("shorts");
}
else
{
System.out.println("jeans");
}
System.out.println("done");
58 > 65 is false, so the else body prints jeans. Then the program continues to the next statement after the whole if-else and prints done.
Braces and semicolons
Always use braces, even when the body is a single statement. Without them, only the single next statement belongs to the if, no matter how the code is indented. Java ignores indentation completely.
int lives = 3;
if (lives == 0)
System.out.println("Game over");
lives = 5;
System.out.println(lives);
Only the println belongs to the if. The line lives = 5; runs every time, so this prints 5 even though the game isn't over. The indentation suggests otherwise, which is exactly why exam questions use this trick.
A semicolon right after the condition is another trap. In if (x > 10); the semicolon is an empty statement that becomes the whole body. The block in braces underneath is then just ordinary code that always runs.
int x = 2;
if (x > 10);
{
System.out.println("big");
}
This prints big even though x is 2.
Writing an if inside a method
In methods, if statements often decide what to return or which instance variable to change. A method can also return a boolean straight from a condition. For example, a method that checks whether a score passes can just return score >= 70; instead of using an if that returns true in one branch and false in the other. Both versions are correct, and readers on the exam accept either.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Tracing if and else
What does this code print when it runs?
int temp = 58; if (temp > 65) { System.out.println("shorts"); } else { System.out.println("jeans"); } System.out.println("done");Show the solutionHide the solution
- Step 1: Evaluate the condition:
temp > 65is58 > 65, which isfalse. - Step 2: Because it's false, Java skips the
ifbody and runs theelsebody, printingjeans. - Step 3: After the
if-else, the next statement always runs, printingdone.
Answer: Two lines:
jeans, thendone. - Step 1: Evaluate the condition:
- Example 2
The missing-braces trap
What does this code print?
int lives = 3; if (lives == 0) System.out.println("Game over"); lives = 5; System.out.println(lives);Show the solutionHide the solution
- Step 1: The condition
lives == 0is3 == 0, which isfalse. - Step 2: Without braces, the
ifcontrols only the next statement, theprintln. That's skipped. - Step 3:
lives = 5;is not part of theif, despite its indentation, so it always runs.livesbecomes 5. - Step 4: The last line prints
lives.
Answer: It prints
5. - Step 1: The condition
Common mistakes
- Trusting indentation. Java only looks at braces, so without them only one statement is controlled by the
if. - Putting a semicolon after
if (...). It ends theifright there, and the block below always runs. - Expecting both branches of an
if-elseto run. Exactly one does.
On the exam
- Tracing questions often hide a missing brace or a stray semicolon. Read the structure before you read the indentation.
- In free-response code, use braces on every
ifandelse, even for one statement. It prevents logic errors.
Connected topics
Videos
Check yourself
4 questions on 2.3 if Statements. Pick an answer to see if you got it, and why.
Consider the following code segment.int x = 4;
if (x > 3)
{
x = x * 2;
}
x = x + 1;
if (x > 10)
{
x = 0;
}
System.out.println(x);What is printed as a result of executing the code segment?
Consider the following method.public static int adjust(int n)
{
if (n % 3 == 0)
{
n = n / 3;
}
else
{
n = n + 2;
}
return n * 2;
}The following code segment appears in another method of the same class.System.out.println(adjust(9) + adjust(4));What is printed as a result of executing the code segment?
A museum charges a fee of 5 for visitors younger than 12 and a fee of 10 for everyone else. Assume the int variables age and fee have been declared and age has been given a value. Which of the following code segments sets fee correctly for every age?
Consider the following code segment.int score = 75;
if (score >= 70)
{
System.out.print("pass ");
}
else
{
System.out.print("retry ");
}
if (score >= 80)
{
System.out.print("bonus");
}
System.out.print("done");What is printed as a result of executing the code segment?
0 of 4 answered