The if else Statements

Basics

The if else Statements

🙋 Need help? Ask an expert now!

Let's start exploring the structure of an if statement in Java by relating it to a real life scenario. Suppose you are walking down the street with an umbrella. We ask one question in order to get a true or false response: "is it raining?". If we answer yes, or "true", then one course of action takes places, we open and use the umbrella. If the answer is no, or "false", another course of action takes place, the umbrella stays closed. This is the basis for an if statement in Java; one of two different courses of action take place based on a "true" or "false" answer. These types of statements involve a binary (two-way) decision. Play with the example below, which uses our umbrella scenario, by changing the boolean "rain" to "false".

IfElseStatementExample.java
package exlcode;

public class IfElseStatementExample {

  public static boolean rain = true;

  public static void main(String[] args) {
    // "== true" can be omitted simplify code
    if (rain == true /* expression */) {
      // "true branch"
      System.out.println("Use your umbrella");
    } else {
      // "false branch"
      System.out.println("Don't use your umbrella");
    }
  }
}

The if statement above tests to see if the boolean value of "rain" is true. If it is, the "true branch" statement is executed. If not, the "false branch" statement is executed. Notice how we separate the "true branch" and the "false branch" by the reserved word else. The expression that goes inside the if statement must evaluate to true or false for the statement to execute, and anything that evaluates to a boolean value can be placed inside brackets.

"If you're tired, go to sleep. Otherwise, stay awake."

"If you're hungry, eat. Otherwise, don't eat."

The if statement allows the programmer to structure results using the same logic we use in our everyday lives.

Edit Me on GitHub!

Application Question

Consider the following code segment:

if (varOne > 0){
  varOne = -varOne;
}
if (varOne < 0){
 varOne = 0;
}

Which of the following is this code segment equivalent to?