Two Mutually Exclusive Branches

Contact Us or call 1-877-932-8228
Two Mutually Exclusive Branches

Two Mutually Exclusive Branches

The if ... else Statement

if (condition) statement;
else if { block } statement;
else { block }

The if ... else Statement does "one thing" if a condition is true, and a different thing if it is false.

It is never the case that both things are done. The "one thing" may be a single statement or a block of statements in curly braces.

A statement executed in a branch may be any statement, including another if or if ... else statement.

If ... Else Statement Flowchart

This program tells you that you are a winner on average once out of every four tries.

Code Sample:

Java-Control/Demos/IfElse1.java
public class IfElse1 {
  public static void main(String[] args) {
    double d = Math.random();
    if (d < .25) System.out.println("You are a winner!");
    else System.out.println("Sorry, try again!");
  }
}

Nested if ... else Statements - Comparing a Number of Mutually Exclusive Options

You can nestif ... else statements, so that an if or else clause contains another test. Both the if and the else clause can contain any type of statement, including another if or if ... else.

You can test individual values or ranges of values. Once an if condition is true, the rest of the branches will be skipped. You could also use a sequence of if statements without the else clauses (but this doesn't by itself force the branches to be mutually exclusive).

Here is the low/middle/high example rewritten using if ... else

Code Sample:

Java-Control/Demos/IfElse2.java
public class IfElse2 {
  public static void main(String[] args) {
    double d = Math.random();
    System.out.print("The number " + d);
    if (d < 1.0/3.0) 
      System.out.println(" is low");
    else if (d < 2.0/3.0) 
      System.out.println(" is middle");
    else 
      System.out.println(" is high");
  }
}

Similarly, we do not test the high third at all. The original version worked because there was no chance that more than one message would print; that approach is slightly less efficient because all three tests will always be made. In the if ... else version, comparing stops once a match has been made.

Next