3.3. Two-way Selection: if-else Statements

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.

 1// A block if/else statement
 2if (boolean expression)
 4   statement1;
 5   statement2;
 9   do other statement;
10   and another one;
1// A single if/else statement
2if (boolean expression)
3    Do statement;
5    Do other statement;

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 1: The order that statements execute in a conditional with 2 options: if and else


The else will only execute if the condition is false.

Assume you are flipping a coin to decide whether to go to a game or watch a movie. If the coin is heads then you will go to a game, if tails then watch a movie. The flowchart in Figure 2 shows the conditional control flow with 2 branches based on a boolean variable isHeads.


Figure 2: If-Else Decision

Run the following code twice for each boolean value for isHeads (true and false). Notice the program always prints “after conditional” since that statement is not nested inside the if or else blocks.

exercise Check your understanding

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.

coding exercise Coding Exercise

Run the following code to see what it prints when the variable age is set to the value 18. Change the input value to 18 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 16 instead of 18? Use 2 test cases for the value of age to test your code to see the results of both print statements.

Recall the program from the previous lesson that outputs a message based on whether you passed the midterm. The program uses two separate if statements to decide what to print. Notice the second condition is simply the negation of the first condition.

Rewrite this code to use a single if-else rather than two separate if statements.

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 <i>Check Me</i> to see if you are right.

coding exercise Coding Exercise

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?

3.3.1. Nested Ifs and Dangling Else

If statements can be nested inside other if statements. Sometimes with nested ifs we find a dangling else that could potentially belong to either if statement. The rule is that the else clause will always be a part of the closest if statement in the same block of code, regardless of indentation.

1// Nested if with dangling else
2if (boolean expression)
3   if (boolean expression)
4       statement1;
5   else  // belongs to closest if
6       statement2;

coding exercise Coding Exercise

Try the following code with a dangling else. Notice that the indentation does not matter. How could you get the else to belong to the first if statement?

You can use curly brackets { } to enclose a nested if and have the else clause belong to the the top level if clause like below:

1// Nested if with dangling else
2if (boolean expression)
4   if (boolean expression)
5       statement1;
7else  // belongs to first if
8   statement2;

3.3.2. groupwork Programming Challenge : 20 Questions


This challenge is on repl.it.

Have you ever played 20 Questions? 20 Questions is a game where one person thinks of an object and the other players ask up to 20 questions to guess what it is.

There is great online version called Akinator that guesses whether you are thinking of a real or fictional character by asking you questions. Akinator is a simple Artificial Intelligence algorithm that uses a decision tree of yes or no questions to pinpoint the answer. Although Akinator needs a very large decision tree, we can create a guessing game for animals using a much smaller number of if-statements.

The Animal Guessing program below uses the following decision tree:


Figure 2: Animal Guessing Game Decision Tree

  1. Try the Animal Guessing program below and run it a couple times thinking of an animal and answering the questions with y or n for yes or no. Did it guess your animal? Probably not! It’s not very good. It can only guess 3 animals. Let’s try to expand it!

  2. In the very last else clause, the program knows that it is not a mammal and it guesses a bird. Let’s add to that part. (You may want to click on Open in Repl.it on the top right of the window and then click on Sign up or Log in to save your work). Instead of saying “I guess a bird! Click on run to play again.”, change it to ask a question that distinguishes between birds and reptiles (for example does it fly?). Then, get their response and use an if statement to guess “bird” or “turtle” (or another reptile). For example, here’s how we decided to choose between a dog or an elephant. We asked the question “Is it a pet?”, got the response, and then with an if statement on the y/n answer we determined dog or elephant. You would use similar code to distinguish between a bird and a turtle. Run your code and test both possibilities!

1System.out.println("Is it a pet (y/n)?");
2answer = scan.nextLine();
3if (answer.equals("y")) {
4     System.out.println("I guess a dog! Click on run to play again.");
5 }
6 else {
7     System.out.println("I guess an elephant! Click on run to play again.");
8 }
  1. Did you notice that when it asked “Is it a pet?” and you said “y”, it immediately guessed “dog”? What if you were thinking of a cat? Try to come up with a question that distinguishes dogs from cats and put in code in the correct place (in place of I guess a dog) to ask the question, get the answer, and use an if/else to guess cat or dog. Run your code and test both possibilities!

  2. How many animals can your game now guess? How many test-cases are needed to test all branches of your code?

After you complete your code on repl.it, paste in your code below to run it through the auto-grader. Also include a link to your code on repl.it in comments.

Copy and paste your code from your repl.it and run to see if it passes the autograder tests. Include the link to your repl.it code in comments. Note that this code will only run with the autograder’s input and will not ask the user for input.

3-3-9: After you complete your code on repl, paste in a link to it (click on share) here.

3.3.3. Summary

  • If statements can be followed by an associated else part to form a 2-way branch:

1if (boolean expression) {
2    Do statement;
4else {
5    Do other statement;
  • A two way selection (if/else) is written when there are two sets of statements: one to be executed when the Boolean condition is true, and another set for when the Boolean condition is false.

  • The body of the “if” statement is executed when the Boolean condition is true, and the body of the “else” is executed when the Boolean condition is false.

  • Use 2 test-cases to find errors or validate results to try both branches of an if/else statement.

  • The else statement attaches to the closest if statement.

You have attempted of activities on this page