RU beehive logo ITEC dept promo banner
ITEC 120
2008spring
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect02c
local variables and named constants

warm-up: We've written PizzaServers that currently know how to answer two questions: Now, let's add the following function to class PizzaServer:
  /** Compute how many square inches of crust a pizza has, given its diameter.
   * @param diam THe diameter of the pizza in question, in inches.
   * @return How much crust the pizza has, in square inches.
   *
   * If 'p' is a PizzaServer instance, then:
   *
   *
   *    
   */
  

      


Local Variables: naming results of partial computations

We've seen examples of computing a partial result, and using that intermediate value as an input to another function. For example, when computing crustArea, we called two other functions, and then subtracted those two sub-results to get our final answer:

double crustArea( double diam ) {
  return this.pizzaArea(diam) - this.toppingArea(diam);
  }
Alternatively, Java allows us to name the two sub-results (the total area, and the non-crust-area):
// Not legal Java code (yet):
double crustArea_v2( double diam ) {
  totalArea = this.pizzaArea(diam);
  innerArea = this.toppingArea(diam);
  return totalArea - innerArea;
  }
This is the exact same computation, but we just attach the names “totalArea” and “innerArea” to the partial results, and then find their difference on the last line. This approach is fine, although Java — always curious about what type things are — needs you to declare these names before you initialize to them.
// legal code now, since we decare the variables we use:
double crustArea_v2( double diam ) {
  double totalArea;              // Total pizza size -- toppings+crust
  totalArea = this.pizzaArea(diam);

  double innerArea;              // The size of the topping-covered area only.
  innerArea = this.toppingArea(diam);

  return totalArea - innerArea;
  }
In general, the syntax for introducing and initializing a name is
type namevariable;
namevariable = expr;
Keep these two lines right next to each other, for now. (We'll see soon that you can combine these two steps into a single line, but for the current week we'll require writing these two steps as two lines, to make it clear that there are two steps happening.)

=” is pronounced “gets”

The character = is pronounced “gets” in Java. It is not the same as equality. In particular, you cannot write something like this.pizzaArea(diam) = totalArea; a variable-name must be on the left-hand-side of =. In a few weeks, we'll see further examples of how = is blatantly different from equality, like i = i+1. Learning to pronounce = “gets” rather than “equals” is a habit which will train your thinking more accurately, and avoid confusion in the future.

Practice

Discuss: Which version do you like better? Why?
Either approach — naming the intermediate results or not — is okay, and fine for this class. You can mix-and-match: Write a single return expression most of the time, and then use local variables for functions that would be too complicated. Also, using local variables to avoid repeated computation is encouraged.

Reminder: When using a local variable to name a sub-result, there are always two lines, side-by-side; after that you can refer back to that sub-result as many times as you like.


parameters, locals, and their scope

We'll get three volunteers, and will role-play what happens when one function calls another. Each function is its own person inside the computer; the only way to interact with the function is to pass it an argument (a number written down on a piece of paper), and get the answer returned (on another piece of paper).

In particular, the function has no idea of how you generated the number you passed to it (and it doesn't care). Conversely, you don't care how the function computes its answer; you just use the answer.

We revisit our solution to last week's lab, where we wrote toppingArea and crustArea. We've updated it a bit to add a couple of local variables (for practice).

/** Functions to calculate the area of pizza purchased, given a diameter.
 *
 * @author Ian Barland
 * @version 2007.Jan.10
 */
class PizzaServer {

  /** Calculate the area of a pizza, given its diameter.
   * @param diam The diameter of the pizza, in inches.
   * @return The area of the pizza, in square inches.
   *    (test cases omitted, to fit on one screen in class)
   */
  double pizzaArea( double diam ) {
    double radius;
    radius = diam/2;
    return 3.14 * radius * radius;
    }


  /** Calculate the are of *topping* on a pizza, given its diameter.
   *  Krusteaze pizza has 3" of crust all the way around.
   * @param diam The diameter of the pizza (in inches); must be 6 or more.
   * @return The amount of topping (in square inches)
   *    (test cases omitted, to fit on one screen in class)
   */
  double toppingArea( double diam ) {
    double toppingDiam;
    toppingDiam = diam - 2*3;
    return this.pizzaArea( toppingDiam );
    /* We subtract the part of the diameter which is crust: 3" on each side. */
    }


  /** Calculate the are of *crust* on a pizza, given its diameter.
   *  Krusteaze pizza has 3" of crust all the way around.
   * @param diam The diameter of the pizza (in inches); must be 6 or more.
   * @return The amount of crust (in square inches)
   *    (test cases omitted, to fit on one screen in class)
   */
  double crustArea( double diam ) {
    return this.pizzaArea(diam) - this.toppingArea(diam);
    }

  }

Practice We'll get three volunteers; if you want to play the role of toppingArea or pizzaArea it helps to have a calculator.
Q: I call crustArea, handing them a sheet of paper with “20” written on it. What happens?

Teacher: You'll want three bold markers, some sheets of blank paper passing and returning results, and these placards (.doc). (The two copies of pizzaArea placard is intentional: it's called twice, with a different input each time.)

Pay close attention to the way pizzaArea is called two separate time -- once with a value of 20, and once with the value of 14.

Discussion points:


1 In this particular example, Java is smart enough to avoid doing the division-by-two twice. But in more complicated situations — where the repeated computation involves calling a function — Java tends not to be smart enough to cache the result, in which case you can do it yourself as shown here. Often, this improves program readability at the same time.      

2This mode of thinking is not a great mode of reasoning about issues with many subtle and intertwined causes, like gender inequities, divorces or other wars.)      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2008, Ian Barland, Radford University
Last modified 2008.Jan.25 (Fri)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme