Chapter 7

Branching

If Statements

If statements cause code to execute only if a given condition is true. The syntax is:

if([condition to test])

{

[code block]

}

For example, this code snippet will print "More than 20" if the value in variable x is greater than 20.

      if (x>20)
      {
        System.out.println("More than 20");
      }
      

Conditions you can test

Comparing primitive types:

== equals (note the difference between this and =, which is used to assign values)
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
!= is not equal to<

Examples:

      if (age >= 18)
      System.out.println("You are old enough to vote”);
      
      if (jerseyNumber == 13)    // {} optional here because only one statement
      {
        String label = "Thirteen";
      }
      
      if (floorNumber != 1)      // {} required here because of multiple statements
      {
        System.out.println(“This is not the first floor”);
        System.out.println(“Please proceed to the first floor”);
      }
      

Comparing Strings (and other objects):

Note that you cannot use the symbols above to compare Strings (and other reference types). Instead, use the equals or compareTo method. For strings, equals returns either true (if two strings have the exact same characters) or false. You will learn about compareTo in a later chapter.

      if (country.equals("Australia"))
      greeting = "G'day, mate!";
      

If-Else

The optional else statement is used to perform an alternative action when the preceding if condition is not met.

For example:

      if (x>20)
      {
        System.out.println("More than 20");
      }
      else
      {
        System.out.println("Not more than 20");
      }
      

The else statement is not required.

There is no stated condition for else (meaning, do not write parentheses after else). It simply executes whenever the if condition is false.

There is also a shortcut called the ternary operator. We do not use this in our course, however, it offers a more concise way write branching code.

Nested If Statements

Sometimes, one condition is nested inside another. For example, consider

      if (x!=0)
      {
      if(x>5) // we only get to this "if" when x!=0
      {
      System.out.println("More than 5");
      }
      else // this "else" goes with the nearest unmatched "if", which is "if(x>5)")
      {
      System.out.println("Less than 5");
      }
      else
      {
      System.out.println("Equals zero"); //this else goes with the first if
      }
      

Note how, if the first condition (on line 1) is met (i.e., if x does not equal 0), then the if statement on line 3 is tested. If not (i.e., if x equals 0), it will skip down to the final else on line 11. Typically, indentation is used to make this clearer, as in

      if (x!=0)
      {
        if(x>5) // we only get to this "if" when x!=0
        {
          System.out.println("More than 5");
        }
        else // this "else" goes with the nearest unmatched "if", which is "if(x>5)")
        {
          System.out.println("Less than 5");
      }
      else
      {
        System.out.println("Equals zero"); //this else goes with the first if
      }
      

Using And, Or, and Not

You can also test multiple conditions using and and or. For “and”, use && and for “or” use || (Shift-backslash on a computer keyboard). && means that both conditions must be true and || means that one (or both) conditions must be true (this is called the inclusive or, as opposed to exclusive or).

      int courseCode = 2271;
      String campus = "Montpelier"; 
      if (courseCode == 2271 && campus.equals("Winooski")) //false,  campus is Montpelier
      System.out.println("You're in course 2271 at Winooski"); //won’t print
      if (courseCode == 2271 || courseCode==2270) //true, this is an “or” statement
      System.out.println("You're in a computer course"); //will print
      

! (the exclamation symbol) on its own is the negation of any logical statement. It creates a condition that is false when the original condition is true, and vice verse. ! is written before the statement, not after. For example,

!(x==4 || y>8) translates to: "it is not true that x equals 4 or y is greater than 8." Notice how the original statement is enclosed in parentheses and the ! is written outside of these.

Else if ("chaining" or "cascading" if)

You can use else if statements to proceed through a series of conditions.

The syntax is:


      if ([condition a])
      {
        //code			//note that if a is true, all following else statements are skipped
      }
      
      else if([condition b])	//note that you get here only if a is false
      {
        //code
      }
      
      else if([condition c])	//note that you only get here if both a and b are false
      {
        //code
      }
      
      /*
      The "else" below goes with the nearest unmatched "if" (i.e., condition c, in this case).
      So, this means that none of the conditions above were met. 
      */
      else
      {
        //code
      }
      

Example in use:

      
      if (temp >= 90)
        System.out.println("Very hot");
      
      else if (temp >= 80) //No need to say (temp < 90), because we wouldn't get here otherwise.
        System.out.println("Hot"):
      
      else if(temp >= 60)
        System.out.println("Mild");
      
      else // meaning (temp <60)
        System.out.println("Cool");
      

An important note about the code above-- you might be wondering why we don’t write instead

      if (temp >= 90)
        System.out.println("Very hot");
      
      if (temp < 90 && temp >= 80) 
        System.out.println("Hot"):
      
      if(temp < 80 && temp >= 60)
        System.out.println("Mild");
      
      if (temp <60)
        System.out.println("Cool");
      

Even though this code would yield the same results as the original, it is inefficient. Why? Suppose the temperature is 92. We would want the code to print “Very hot” and be done with it. But, in the second version, it would still test all the other conditions. The advantage of “else if” is that once a condition is met, all other conditions are skipped.

Switch statements

Another way to control program flow based on a set of conditions is the switch statement, which is explained well here.