Java Lesson 7: Conditionals (Selection Statements)

1
21

Introduction

Many of our examples so far have been simple sequential programs with code that proceeds in a linear fashion, such as:

Rarely does a real program just go through a single series of steps to produce its output. In order to have interaction, programs must react to input and calculations, and make decisions about what code to execute next. In addition, if you need to repeat a code fragment several times in a row, it is inefficient (and a lot of typing) to keep repeating it. Control flow makes your program move through the steps needed in the correct order. Java provides conditional selection statements and, as we will see in the next lesson, iterative looping statements, for these situations.

Review of Logical Expressions

Before considering the detailed conditional and iterative statements, let’s review some concepts presented in Lesson 5 Operators and Expressions that are used with these statements.

We need to form logical expressions that are either true or false. To do so, we can use the relational operators, <, >, <=, >=, and the equality operators, == and !=. Here are several logical expression examples.

Expressions such as these are extensively throughout this and the next lesson.

Types of Conditional Selection Statements

Java has two conditional selection statements: if-else and switch, which allow you to control the program’s execution based upon a variable’s value at run time. Also, the break statement is sometimes used in switch statements.

The if-else Branch

The if statement is used to direct program execution through one of two different paths. The if-else statement has the general form:

Recall that a condition is any expression that returns a boolean value (true or false). For example:

Here, if a is less than b, then a is set equal to b, otherwise b is set equal to a. Only one path is taken – either a = b; or b = a;.

Most often, the expression used to control the if will be a relational operator. However, it can also be a single boolean variable, as shown below:

Technically speaking, if there is only one statement executed after an if or else, then you do not need the curly braces { }; however it is good practice to use them regardless because it makes the code easier to read and you may want to add another statement at a later time.

The else clause is optional. The following code fragment is a valid selection statement:

A nested if is an if statement that is the target of another if or else. These can become arbitrarily deep and complicated.

Use curly braces to make Nested if statements easier to understand.

You can string together a series of tests, known as an in-else-if ladder, as shown here:

In this case, the Boolean expressions at each stage are evaluated. If one is found to be true, it is executed; otherwise, the final else is executed.

Suppose we wish to write a game program which mimics at game show. We will prompt the user to select Door Number 1, Door Number 2, or Door Number 3. The user wins a different prize depending upon which door they choose. If the user selects the first door, then they will win a car. If the user selects the second door, then they will win a pet. If the user selects the third door, then they get “zonked” (this is a bad prize). Finally, the program will tell the user which prize they won and whether it is a good prize or a bad prize. Program7a.java does just that.

Let’s examine the program in detail:

Line 11, as we learned in the previous lesson, creates a scanner to read input from the keyboard.

Lines 14 and 15 prompt the user to enter a door number, and stores the user’s entry in the variable num.

Lines 17 and 18 declare and initialize two more variables; a boolean for whether the prize is a good prize or not, and a String which holds text to describe what prize they won.

Lines 20 through 33 are the heart of the program.  An if-else-if ladder tests the variable num to see if it is 1, 2, 3, or an invalid entry (e.g., some other number).

Lines 36 to 42 display the value of winText, and whether it is a good prize or not.

Running Program7a gives the following results:

Execution of Program7a

An if statement can test for more than one condition at a time by using a Boolean Logical operator such as && (short-circuit AND) or || (short-circuit OR).

Program7b demonstrates testing multiple conditions to determine what season a given month number (1 through 12) is. This program would be much longer with 12 if statements.

Execution of Program7b.

The switch Branch

The switch branch is a kind of if-else-if structure, but makes programming easier than writing out many if-else conditions. It is also called a multi-way branch statement. The form of the switch branch is:

The switch executes by comparing the value of the expression in the switch parenthesis with the values listed for each case, and executing the statement that occurs at the matching case. If none of the values match, the default: case executes. The default case is optional. The expression must be of type byte, short, int, char, an enumeration, or String (JDK 7 or later). After each case, you usually will use a break statement; otherwise all the cases after the one that matches will execute. This is called drop-through. Switch statements can be nested (i.e., a switch statement inside of another switch statement).

Let’s refactor (rewrite) the first program in this tutorial to use a switch instead of multiple if conditional statements.

Execution of Program7c.

As an exercise, enter this program on your computer and run it. Then, remove the break statements (or simply comment them out by putting “//” at the beginning of each line that has a break) and see what happens:

Execution of Program7c with the break statements removed.

As you can see, even though the user entered a valid door number, the program acts as if they didn’t. Without the break statements, all the case options are executed, including the last one (the default), which sets the variables WinText and goodPrize.

The break and default statements are optional, and as we just saw, forgetting the break statements could produce unintended results. However, this is a useful technique for some programs. For example, the following program deliberately omits some break statements and the default statement to decide if the user’s input is an even or an odd number:

Execution of Program7d which determines if the user's input is an even or an odd number.

Summary

In this lesson we learned about Java’s two conditional selection statements, if-else and switch, which allow you to control the program’s execution by branching to different sections of code depending upon conditions at execution time.

Next Lesson

Next we will move on to Loops (Iterative Statements).

1 COMMENT

Leave a Reply