πŸ““3.4: Else If Statements

Table of Contents


πŸ“– This page is a condensed version of CSAwesome Topic 3.4

πŸ“ Take notes in a Codespace during class, coding along with the instructor.

  1. Go to GitHub and click on your picture in the TOP RIGHT corner
  2. Select Your repositories
  3. Open CS2-Unit-3-Notes
  4. Now on your repository, click and select the Codespaces tab
  5. Click Create Codespace on main (unless you already have one listed there), wait for the environment to load, then you’re ready to code!

Multi-Selection: else-if Statements

Using if/else statements, you can even pick between 3 or more possibilites. Just add else if for each possibility after the first if, and else before the last possibility.

// 3 way choice with if, else if, else
if (boolean expression) {
  statement1;
}
else if (boolean expression) {
  statement2;
}
else {
  statement3;
}

Run the code below and try changing the value of x to get each of the three possible lines in the conditional to print.

int x = 2;
if (x < 0) {
  System.out.println("x is negative");
}
else if (x == 0) {
  System.out.println("x is 0");
}
else {
  System.out.println("x is positive");
}
System.out.println("after conditional");

Here is a flowchart for a conditional with 3 options like in the code above:

image

Another way to handle 3 or more conditional cases is to use the switch and case keywords, but these will not be on the exam. For a tutorial on using switch see the Java Documentation.

Finish the following code so that it prints β€œPlug in your phone!” if the battery is below 50, β€œUnplug your phone!” if it is equal to 100, and β€œAll okay!” otherwise. Change the battery value to test all 3 conditions.

int battery = 60;

System.out.println("All okay!");

⭐️ Summary

  • A multi-way selection is written when there are a series of conditions with different statements for each condition.

  • Multi-way selection is performed using if-else-if statements such that exactly one section of code is executed based on the first condition that evaluates to true.

// 3 way choice with if, else if, else
if (boolean expression) {
  statement1;
}
else if (boolean expression) {
  statement2;
}
else {
  statement3;
}

πŸ›‘ When class ends, don’t forget to SAVE YOUR WORK!

  1. Navigate to the Source Control menu on the LEFT sidebar
  2. Type a brief commit message in the box, for example: updated Main.java
  3. Click the button on the LEFT menu
  4. Click the button on the LEFT menu
  5. Finally you can close your Codespace!

Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.