# 2.3 if Statements

Each coding exercise has its own folder. Open its `.java` file and press **Run** to try it. **Run Tests** checks every graded exercise in this lesson at once.

**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.

![Comparison of App Inventor if block, AP CSP ifs, and Java if statements](images/BlocksIfComparison.png)

*Comparison of App Inventor if block, AP CSP ifs, and Java if statements*

## 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.

![The order that statements execute in a conditional](images/Condition.png)

*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.

```java
// 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 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).

### Exercise 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 to see this.

> Open the `01-if-raining` folder and run `Test1.java`. It is an example, so it has no tests.

> Check your understanding: Try changing the code in `01-if-raining` to `boolean isRaining = false;`. What will it print? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-3-ifs.html#iffalseOutput

## Relational Operators in If Statements

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

### Exercise 2

Run the 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.

> Open the `02-if-relational` folder and edit `TestNumbers.java`. Press **Run** to try it; **Run Tests** checks it (3 tests).

> 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.

> Check your understanding: Consider the following code segment. What is printed as a result of executing the code segment?
>
> ```java
> int x = 3;
> if (x > 2)
> {
>    x = x * 2;
> }
> if (x > 4)
> {
>    x = 0;
> }
> System.out.print(x);
> ```
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-3-ifs.html#mcq-if-trace

## 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.

```java
// A block if/else statement
if (boolean expression)
{
   statement1;
   statement2;
}
else
{
   do other statement;
   and another one;
}
```

```java
// 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.

![The order that statements execute in a if/else statement](images/Condition-two.png)

*The order that statements execute in a if/else statement*

### Exercise 3

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

> Open the `03-ifHeads` folder and run `Test2.java`. It is an example, so it has no tests.

> Check your understanding: Try changing the code in `03-ifHeads` to `boolean isHeads = false;`. What line will be printed before `after conditional`? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-3-ifs.html#falseElse

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.

### Exercise 4

Run the 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.

> Open the `04-licenseifelse` folder and edit `DriversLicenseTest.java`. Press **Run** to try it; **Run Tests** checks it (1 test). Its test checks your code, not what it prints: “check age >= 15”.

> Check your understanding: 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. — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-3-ifs.html#ifelseevenOdd

### Exercise 5

Try the 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?

> Open the `05-scoreifelse` folder and edit `ScoreTest.java`. Press **Run** to try it; **Run Tests** checks it (5 tests).

## 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.

### Exercise 6

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

> Open the `06-if-missing-curlies` folder and edit `Test1.java`. Press **Run** to try it; **Run Tests** checks it (2 tests).

## Coding Challenge: Magic 8 Ball

![Magic 8 Ball](images/Magic_eight_ball.png)

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](https://magic-8ball.com/). 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](/lessons/CSA-1.11-Using-the-Math-Class) and remember the formula `(int) (Math.random() * max) + min`.

### Exercise 7

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.

> Open the `07-challenge-Magic8ball` folder and edit `Magic8Ball.java`. Press **Run** to try it; **Run Tests** checks it (4 tests).

You can make this code more interactive by using the `Scanner` class to have the user ask a question first.

## 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.

```java
// 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:

  ```java
  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.

## AP Practice

> Check your understanding: Consider the following code segment.
>
> ```java
> 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?
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-3-ifs.html#AP2-3-1

> Check your understanding: Consider the following code segment.
>
> ```java
> 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?
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-3-ifs.html#AP2-3-2

> Check your understanding: 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.
>
> ```java
> 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?
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-3-ifs.html#AP2-3-if-else
