Control Structures

Flow of Control:

Flow of control through a program segment is implemented with three basic types of control structures:

Useful tools for building programs or program segments

Logical Operators:

The arithmetic comparison operators in Java work much like the symbols we use in mathematics.  Each of these operators returns a Boolean value: a true or a false.
  x == y        // x is equal to y
  x != y        // x is not equal to y
  x < y         // x is less than y
  x <= y        // x is less than or equal to y
  x > y         // x is greater than y
  x >= y        // x is greater than or equal to y

We also have Boolean operators for combining expressions.  Again, these operators return true or false

  !x            // the not operator (negation) -- true if x is false
  x && y        // the and operator -- true if both x and y are true
  x || y        // the or operator -- true if either x or y (or both) are true
  x ^ y         // the exclusive or operator -- true if exactly one operand is true and one is false

  x & y         // the unconditional and operator 
  x | y         // the unconditional or operator
Unconditional versions of AND and OR are just like regular ones, except they always evaluate both operands

These operators will be commonly used as test expressions in selection statements or repetition statements (loops).
 


Selection Statements:

The if statment:
   if (boolean expression)
   {
      statement(s)
   }
The if/else statement:
   if (boolean expression)
   {
      statement(s)
   }
   else
   {
      statement(s)
   }

Note: In both of these, the set braces can be left out if the "body" of the if or the else is a single statement. Otherwise, the block is needed.


Examples:

  if (grade >= 68)
    System.out.print("Passing");

// Notice that there is no else clause.  If the grade is below 68, we move on.


  if (x == 0)
    System.out.println("Nothing here");
  else
    System.out.println("There is a value");

// This example contains an else clause.  The bodies are single statements.


  if (y != 4)
  {
    System.out.println("Wrong number");
    y = y * 2;
    counter++;
  }
  else
  {
    System.out.println("That\'s it!");     
    success = true;
  }

Multiple statements are to be executed as a result of the condition being true or false.  In this case, note that the blocks are needed.



Be careful with ifs and elses.  Here's an example of an easy mistake to make.  If you don't use { }, you may think that you've included more under an if condition than you really have.

// What output will it produce if val = 2?   Does the "too bad" statement really go with the "else" here?

  if (val < 5)
    System.out.println("True");
  else
    System.out.println("False");
    System.out.println("Too bad!");

* Indentation is only for people!  It improves readability, but means nothing to the compiler.

Miscellaneous if/else examples


The Switch Statement

Good for occasions in which you are selecting among many different choices of values. Format:
switch (expression)
{ 
    case constant: 
        statements 
    case constant: 
        statements 

    ...  (as many case labels as needed) 

    default:            // optional label 
        statements 
} 

The switch statement evaluates the expression, and then looks for a match in the case labels. If it finds a match, execution of code jumps to that case label. The values in case labels must be constants. The switch expression may evaluate to one of these types: char, byte, short, int. If you want to execute code only in the case that you jump to, remember to end the case with a break statement!

Switch Example 1 -- syntactically correct, but logically incorrect

Switch Example 2 -- corrected version of Example 1

Example 3:  This examples uses character literals for the case labels. It also allows for both upper and lower case menu choices.

  System.out.print("Enter menu choice: "); 
  MyInput.readChar(option); 
  switch(option) 
  { 
    case 'A': 
    case 'a': 
        result = a + b; 
        break; 
    case 'S': 
    case 's': 
        result = a - b; 
        break; 
    case 'M': 
    case 'm': 
        result = a * b; 
        break; 
    default: 
        result = 0; 
  } 

Conditional Expressions

Java, like C++, has a ternary operator (i.e. three operands) that evaluates a condition and returns one of two values, based on the condition. This is the ?: operator. Format:
  booleanExpression ? expression1 : expression2
If the boolean expression is true, expression1 is the result of the operation. Otherwise, expression 2 is the result.

Example 1:

  y = (x > 10 ? 5 : 3);
This statement above is equivalent to:
  if (x > 10)
    y = 5;
  else
    y = 3;
Example 2:
  System.out.print((num >= 0) ? "num is non-negative" : "num is negative");
Note that this is equivalent to:
  if (num >= 0)
    System.out.print("num is non-negtative");
  else
    System.out.print("num is negative");

Repetition Statements:

Repetition statements are handled with some type of loop.  The three basic types are while, do/while, and for loops.
In all of these syntax formats, the boolean expression is often known as the loop continuation condition, and the loop body must be a block or a single statement.

Formats:

 while (boolean expression) 
 {
   statement(s)
 } 


 do 
 {
   statement(s)
 } 
 while (boolean expression); 
  

 for (initial condition; boolean expression; iterative statement) 
 {
   statement(s)
 } 


Examples:  Each of the following loops adds up all of the numbers between 1 and 50.  However, here are three separate ways of doing it.

 // while loop example 
 // loop body runs 50 times, condition checked 51 times 
 int i = 1, sum = 0; 
 while (i <= 50) 
 { 
    sum += i; 
    i++; 
 } 
 System.out.println("Sum of numbers from 1 through 50 is " + sum); 
  

 // do/while loop example 
 // loop body runs 50 times, condition checked 50 times 
 int i = 1, sum = 0; 
 do 
 { 
    sum += i; 
    i++; 
 } while (i <= 50); 
 System.out.println("Sum of numbers from 1 through 50 is " + sum); 
  

 // for loop example 
 // loop body runs 50 times, condition checked 51 times 
 int sum = 0; 
 for (int i = 1; i <= 50; i++) 
 { 
    sum += i; 
 } 
 System.out.println("Sum of numbers from 1 through 50 is " + sum); 

Special notes about for loops:

1) It should be noted that if the control variable is declared inside the for header, it only has scope (i.e. it only exists) through the for-loop's execution. Once the loop is finished, the variable no longer exists:
  for (int counter = 0; counter < 10; counter++) 
  {    (loop body)    } 

  // The variable "counter" is now out of scope - it cannot be used here 

This can be avoided by declaring the control variable before the loop itself.

  int counter;    // declaration of control variable 

  for (counter = 0; counter < 10; counter++) 
  {    (loop body)    } 

  // The variable "counter" is still exists here

2) For loops also do not have to count one-by-one, or even upward. Examples:

  for (i = 100; i > 0; i--)
  for (c = 3; c <= 30; c+=4)

The first example gives a loop header that starts counting at 100 and decrements its control variable, counting down to 1 (and quitting when i reaches 0). The second example shows a loop that begins counting at 3 and counts by 4's (the second value of c will be 7, etc).


Special statements:  break and continue

These two special statements alter the normal flow of control in some of the above structures.

Code Examples