Previous Table of Contents Next


13.5. Flow of Control

“Flow of control” is the term for deciding which statements in a program are executed. The while loop in the Fibonacci program above is one way. Other flow-of-control statements include if/else, for, switch, do/while, and blocks—multiple statements grouped within { and }. We change the Fibonacci sequence program by numbering the elements of the sequence, and marking even numbers with an asterisk:

   class ImprovedFibonacci {
        /** Print out the first few Fibonacci
          * numbers, marking evens with a ‘*’ */
        static final int MAX_INDEX = 10;

        public static void main(String[] args) {
             int lo = 1;
             int hi = 1;
             String mark;

             System.out.println(“1: “ + lo);
             for (int I=2; I < MAX_INDEX; I++) {
                  if (hi % 2 == 0_
                      mark = “ *”;
                  else
                      mark = “”;
                  System.out.println(i + “: “ + hi + mark);
                  hi = lo + hi;          // new hi
                  /* new lo is (sum - old lo) i.e., the old hi */
                  lo = hi - lo;
             }
        }
   }

Here is the new output:

   1: 1
   2: 1
   3: 2 *
   4: 3
   5: 5
   6: 8 *
   7: 13
   8: 21
   9: 34 *

To number the elements of the sequence, we used a for loop instead of a while loop. A for loop is shorthand for a while loop, but with an initialization and increment phase added. The for loop above is equivalent to this while loop:

   {
        int I = 2;
        while (I < MAX=INDEX) {
             // .. do the printing stuff
             I++;
        }
   }

The ++ operator in the code fragment above may be unfamiliar if you’re new to C-derived programming languages. The plus-plus operator increments by one the value of any variable it abuts—the contents of variable i in this case. The ++ operator is a prefix operator when it comes before its operand, and postfix when it comes after. Similarly, minus-minus decrements by one the value of any variable it abuts, and can also be prefix or postfix. The ++ and operators come from the C programming language. In the context of the example above, a statement like

   i++;

is equivalent to

   i = i + 1;

Beyond simple assignment, Java supports other assignment operators that apply an arithmetic operation to the value on the left-hand side of the operator. For example, another way to write i++ in the for loop above would be to write

   i += 1;

which adds the value on the right-hand side of the += operator (namely 1) to the variable on the left-hand side (namely i). Many of the binary operators in Java (operators that take two operands) can be joined with the = in a similar way.

Inside the for loop we use an if/else to see if the current hi value is even. The if statement tests the expression between the parentheses. If the expression is true, the first statement or block in the body of the if is executed. If the expression is false, the statement or block following the else clause is executed. The else part is optional: If the else is not present, nothing is done when the expression is false. After figuring out which (if any) clause to execute, control passes to the code following the body of the if statement.

The example tests if hi is even, using the % or remainder operator. It produces the remainder after dividing the value on the left side by the value on the right. If the left-side value is even, the remainder is 0, and the following statement assigns a string containing the even-number indicator to marker. The else clause is executed for odd numbers, setting marker to an empty string.

The println invocation is more complex, using the + operator to concatenate strings representing i, a separator, a string representing hi, and the marker string. The + operator is a concatenation operator when used with strings, whereas it is an addition operator when used in arithmetic expressions.

Exercise 13.7

Change the loop so that i counts backward instead of forward.

13.6. Classes and Objects

Java, like any object-oriented programming language, provides a tool to solve programming problems using the notions of classes and objects. Objects in Java have a type; that type is the object’s class. Each class type has two kinds of members, namely, fields and methods.

  Fields are data variables associated with a class and its objects. Fields store results of computations performed by the class’s methods.
  Methods contain the executable code of a class. Methods are built from statements. The way in which methods are invoked and the statements contained within those methods are what ultimately directs program execution.

Here is the declaration of a simple class that might represent a point on a two-dimensional plane:

   class Point {
        public double x, y;
   }

This Point class has two fields representing the x and y coordinates of a point, and has (as yet) no methods. A class declaration like this one is, conceptually, a plan that defines what objects manufactured from that class look like, plus sets of instructions that define the behavior of those objects. The blueprint of an object adds its maximum value when you use the plans and instructions in the blueprint to manufacture goods (objects) from those plans.

Members of a class can have various levels of visibility. The public declaration of x and y in the Point class means that any code with access to a Point object can read or modify those values. Other levels of visibility limit member access to code in the class itself, or to other related classes.


Previous Table of Contents Next