Skip to main content
Logo image

Section 2.3 if Statements

90 minutes
If statements are found in all programming languages as a way to choose between different paths in an algorithm. An if statement is a type of selection statement that changes the sequential execution. It affects the flow of control by executing different segments of code based on the value of a Boolean expression.
If you took an AP CSP course or used a block programming language like Scratch, you’ve probably seen if blocks or statements before. Here’s a comparison of ifs in App Inventor blocks, AP CSP block code and pseudocode, and Java ifs.
Figure 2.3.1. Comparison of App Inventor if block, AP CSP ifs, and Java if statements

Subsection 2.3.1 One-way selection

A one-way selection (if statement) is used when there is a segment of code (called the body of the if statement) to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true. If the Boolean expression is false, the body of the if statement is skipped and the program continues with the next statement after the if statement.
Figure 2.3.2. The order that statements execute in a conditional
The open curly brace { and a close curly brace } are used to group a block of statements together as the body of the if statement. It is recommended to always put in the curly braces even if you have just one statement under the if statement. The questions you will see on the AP exam will use curly braces.
// A single if statement
if (boolean expression)
    Do statement;
// Or a single if with {}
if (boolean expression)
{
   Do statement;
}
// A block if statement: { } required
if (boolean expression)
{
   Do Statement1;
   Do Statement2;
   ...
   Do StatementN;
}

Note 2.3.3.

Note that there is no semicolon (;) at the end of the boolean expression in an if statement even if it is the end of that line. The semicolon goes at the end of the whole if statement, often on the next line. Or { } are used to mark the beginning and end of the block of code under the if condition.
Imagine that your cell phone wanted to remind you to take an umbrella if it was currently raining in your area when it detected that you were leaving the house. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI) or Ubiquitous Computing (computers are everywhere).

Activity 2.3.1.

The variable isRaining is a boolean variable that is either true or false. If it is true then the message Take an umbrella! will be printed and then execution will continue with the next statement which will print Drive carefully. Run the code below to see this.

Activity 2.3.2.

Subsection 2.3.2 Relational Operators in If Statements

Most if statements have a boolean condition that uses relational operators like ==, !=, <, >, <=, >=, as we saw in the last lesson.

Activity 2.3.3.

Run the following active code a couple times until you see all the possible outputs. It prints out whether a random number is positive or equal to 0. Add another if statement that tests if it is a negative number.

Note 2.3.4.

A common mistake in if statements is using = instead of == in the condition by mistake. You should always use ==, not =, in the condition of an if statement to test a variable. One equal sign (=) assigns a value to a variable, and two equal signs (==) test if a variable has a certain value.

Activity 2.3.4.

Consider the following code segment. What is printed as a result of executing the code segment?
int x = 3;
if (x > 2)
{
   x = x * 2;
}
if (x > 4)
{
   x = 0;
}
System.out.print(x);
  • 3
  • x is changed by the if statements.
  • 6
  • What happens when x is greater than 2 and then greater than 4? Do both if statements.
  • 0
  • If x is greater than 2, it’s always doubled, and then that result is always greater than 4, so it’s set to 0 in the second if statement.
  • 4
  • x is changed by the if statements.
  • The code will not compile
  • This code will compile.

Subsection 2.3.3 Two-way selection

What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might flip a coin and do one thing if it lands as heads and another if it is tails. In programming, you can use the if keyword followed by a statement or block of statements and then the else keyword also followed by a statement or block of statements.
// A block if/else statement
if (boolean expression)
{
   statement1;
   statement2;
}
else
{
   do other statement;
   and another one;
}
// A single if/else statement
if (boolean expression)
    Do statement;
else
    Do other statement;
A two-way selection (if-else statement) is used when there are two segments of codeβ€”one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.
The following flowchart demonstrates that if the condition (the boolean expression) is true, one block of statements is executed, but if the condition is false, a different block of statements inside the else clause is executed.
Figure 2.3.5. The order that statements execute in a if/else statement

Activity 2.3.5.

Try the following code. If isHeads is true it will print Let's go to the game and then after conditional.

Activity 2.3.6.

If/else statements can also be used with relational operators and numbers like below. If your code has an if/else statement, you need to test it with 2 test-cases to make sure that both parts of the code work.

Activity 2.3.7.

Run the following code to see what it prints out when the variable age is set to the value 16. Change the variable age’s value to 15 and then run it again to see the result of the print statement in the else part. Can you change the if-statement to indicate that you can get a license at age 15 instead of 16? Use 2 test cases for the value of age to test your code to see the results of both print statements.

Activity 2.3.8.

The following program should print out β€œx is even” if the remainder of x divided by 2 is 0 and β€œx is odd” otherwise, but the code is mixed up. Drag the blocks from the left and place them in the correct order on the right. Click on Check Me to see if you are right.

Activity 2.3.9.

Try the following code. Add an else statement to the if statement that prints out β€œGood job!” if the score is greater than 9. Change the value of score to test it. Can you change the boolean test to only print out β€œGood job” if the score is greater than 20?

Subsection 2.3.4 Common Errors with If Statements

Here are some rules to follow with if statements to avoid some common errors:
  • Always use curly braces ({ and }) to enclose the block of statements under the if condition. Java doesn’t care if you indent the codeβ€”it goes by the { }.
  • Don’t put in a semicolon ; after the first line of the if statement, if (test);. The if statement is a multiline block of code that starts with the if condition and then { the body of the if statement }.
  • Always use ==, not =, in the condition of an if statement to test a variable. One = assigns, two == tests!
  • The else statement matches with the closest if statement. If you want to match an else with a different if statement, you need to use curly braces to group the if and else together.

Activity 2.3.10.

The code below doesn’t work as expected. Fix it to only print Wear a coat and Wear gloves when isCold is true.

Subsection 2.3.5 Coding Challenge: Magic 8 Ball

Have you ever seen a Magic 8 ball? You ask it a yes-no question and then shake it to get a random response like Signs point to yes!, Very doubtful, etc. If you’ve never seen a Magic 8 ball, check out this simulator. In the exercise below, come up with 8 responses to yes-no questions. Write a program below that chooses a random number from 1 to 8 and then uses if statements to test the number and print out the associated random response from 1-8. If you need help with random numbers, see the Math lesson and remember the formula (int) (Math.random() * max) + min.

Project 2.3.11.

Complete the printRandomResponse() method to print out 1 of 8 random responses and the lucky() method to toss a coin and print out β€œLucky!” or β€œNo Luck!” based on the result. Run the code multiple times to see the responses.
You can make this code more interactive by using the Scanner class to have the user ask a question first; you can try your code with input in JuiceMind or replit or a local IDE.

Subsection 2.3.6 Summary

  • (AP 2.3.A.1) Selection statements change the sequential execution of statements.
  • (AP 2.3.A.2) An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression.
  • (AP 2.3.A.3) A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.
  • if statements test a boolean expression and if it is true, go on to execute the body which is the following statement or block of statements surrounded by curly braces ({}) like below.
// A single if statement
if (boolean expression)
    Do statement;
// A block if statement
if (boolean expression)
{
   Do Statement1;
   Do Statement2;
   ...
   Do StatementN;
}
  • Relational operators (==, !=, <, >, <=, >=) are used in boolean expressions to compare values and arithmetic expressions.
  • If statements can be followed by an associated else part to form a 2-way branch:
if (boolean expression)
{
    Do statement;
}
else
{
    Do other statement;
}
  • (AP 2.3.A.4) A two-way selection (if-else statement) is used when there are two segments of codeβ€”one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.

Subsection 2.3.7 AP Practice

Activity 2.3.12.

Consider the following code segment.
int speed = 35;
boolean rain = false;

if (rain)
{
   speed -= 10;
}

if (rain == false)
{
  speed += 5;
}

if (speed > 35)
{
   speed = speed - 2;
}

System.out.println(speed);
What is printed as a result of executing the code segment?
  • 28
  • Some of the if statement conditions are false so they will not run.
  • 35
  • Take a look at the changes to speed in the if statements.
  • 38
  • Correct! The first if statement condition is false, and the second and third if conditions are true.
  • 25
  • The first if statement would only run if rain is true.
  • 33
  • The second if statement would run since rain is false.

Activity 2.3.13.

Consider the following code segment.
int x = 5;

if (x < 5)
{
   x = 3 * x;
}

if (x % 2 == 1)
{
   x = x / 2;
}

System.out.print(2*x + 1);
What is printed as a result of executing the code segment?
  • 3
  • Take a look at the second if statement again!
  • 11
  • Take a look at the second if statement again!
  • 31
  • The first if statement condition is false.
  • 15
  • The first if statement condition is false.
  • 5
  • Correct! The first if statement is not true. The second one is true since 5 is odd, and x becomes 2. And 2*2 + 1 = 5 is printed out.

Activity 2.3.14.

Consider the following code segment where a range of β€œHigh”, β€œMiddle”, or β€œLow” is being determined where x is an int and a β€œHigh” is 80 and above, a β€œMiddle” is between 50 - 79, and β€œLow” is below 50.
if (x >= 80)
{
   System.out.println("High");
}

if (x >= 50)
{
  System.out.println("Middle");
}
else
{
   System.out.println("Low");
}
Which of the following initializations for x will demonstrate that the code segment will not work as intended?
  • 80
  • This would print out both β€œHigh” and β€œMiddle”, showing that there is an error in the code. As you will see in the next lesson, one way to fix the code is to add another else in front of the second if.
  • 60
  • This would correctly print out β€œMiddle”.
  • 50
  • This would correctly print out β€œMiddle”.
  • 30
  • This would print out β€œLow” which is correct according to this problem description.
  • -10
  • This would print out β€œLow” which is correct according to this problem description.
You have attempted of activities on this page.