3.2. If Statements and Control Flow

The statements in a Java main method normally run or execute one at a time in the order they are found. If statements (also called conditionals or selection) change the flow of control so that certain lines of code only run when something is true. An if statement checks a boolean condition that is either true or false. A block of statements will execute if the condition is true and will be skipped if the condition is false.

../_images/Condition.png

Figure 1: The order that statements execute in a conditional

A conditional uses the keyword if followed by Boolean expression inside of an open parenthesis ( and a close parenthesis ) and then followed by a single statement or block of statements. The single statement or block of statements are only executed if the condition is true. The open curly brace { and a close curly brace } are used to group a block of statements together. It is recommended to always put in the curly braces even if you have just one statement under the if statement.

1 statement 1 statement 2+ statements
{} optional {} optional {} required
if (x<10) if (x<10) if (x<10)
   count++; { {
   count++;    count++;
}    System.out.println(count);
}

Note

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

The variable isRaining is a boolean variable that is either true or false. Use the CodeLens to step through the code.

exercise Check your understanding

You can test for a false value using the ! operator, which is read as “not”. We will see a better way to test for both true and false in the next lesson. However, the code below shows how to print different messages based on whether a value is true or false.

This program reads in a boolean value from standard input and tests whether the value is true if (passedExam) or false if (!passedExam). Use the CodeLens to step through the program. Change the value in the standard input window to test the program with each possible boolean value.

Note

In an if statement, it is good style to indent the lines of code nested between the curly braces.

exercise Check your understanding

3.2.1. Relational Operators in If Statements

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

coding exercise Coding Exercise

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

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.

exercise Check your understanding

3.2.2. Conditional Control Flow

Recall the program to compute the number of pizza slices per person from Unit 1.

Run the program to confirm that it fails when a value of 0 is entered for numPeople (second input value).

To avoid division by 0, the calculation for slicesPerPerson and leftoverSlices should be skipped when the number of people is 0. In fact, the calculation is nonsense if the number of people is a negative number so the program should check if a positive value is read from input. The program should actually ensure positive values are input for both the number of people and number of pizza slices, but for now you will only test the number of people. You will see how to test compound boolean expressions in a later lesson.

../_images/flow_3.png

Figure 2: Conditional Control Flow

The flowchart in Figure 2 demonstrates the desired control flow based on an if statement, represented with a diamond symbol. If the condition numPeople > 0 is true, the process follows the path labelled true, which contains the 4 steps to calculate and print slicesPerPerson and leftoverSlices. The 4 statements along the true branch must be nested within curly braces in a Java program otherwise only the first step would be considered part of the true branch. If the condition numPeople > 0 is false, the false branch is followed and the 4 statements for calculating and printing are skipped.

Update the program based on the conditional control flow shown in Figure 2. Add an if statement to test the value stored in numPeople. Don’t forget curly braces around the 4 lines for computing and printing slicesPerPerson and leftoverSlices.

Run the program multiple times with negative, 0, and positive values for number of people. The program should no longer result in a divide by zero exception.

3.2.3. Common Errors with If Statements

Here are some rules to follow to avoid common errors:

  • Always use curly brackets { 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!

coding exercise Coding Exercise

The code below doesn’t work as expected. It has 2 errors. Run the program with input true, then change the input to false and run again. Even when the input is false, the program still prints both messages. Fix it to only print both “Wear a coat” and “Wear gloves” when isCold is true. Nothing should print when isCold is false.

3.2.4. groupwork Programming Challenge : Magic 8 Ball

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

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

For an extra challenge, have the program create a Scanner and read the question from standard input before generating a response. Repeat the user’s question as part of the response.

3.2.5. Summary

  • if statements test a boolean expression and if it is true, go on to execute the following statement or block of statements surrounded by curly brackets { } like below.

// A single if statement
if (boolean expression)
    Do statement;
// A block if statement
if (boolean expression)
{
   Do Statement1;
   Do Statement2;
   ...
   Do StatementN;
}
  • Java boolean expressions can compare primitive values and reference values with the relational operators == and != and arithmetic expression values with the relational operators (i.e., <, >, <=, >=).

  • Conditional (if) statements affect the flow of control by executing different statements based on the value of a Boolean expression.

You have attempted of activities on this page