Experiment 9: Declarations

Given the ability to construct expressions, it becomes useful to be able to store the value of an expression. That is, if we have an expression whose value is needed several times, it is most time-efficient to evaluate the expression once, store its value, and then access the stored value, rather than spending time reevaluating the expression.

To illustrate, suppose that our problem involves two constant data objects: p and 2p. The inefficient way is to write the value of p and re-compute 2p each time they are needed:

   // use 3.14159 and re-compute 2.0 * 3.14159 each time it is needed

By contrast, a more efficient approach is to compute and store p and 2p once with a statement called a variable declaration:

   double pi = 3.14159,
          twoPi = 2.0 * pi;

and then use these names each time their values are needed:

   // use pi and twoPi each time they are needed

This has two benefits:

Take a moment and place this declaration in Express.java. Then modify the output statement to display the values of piand twoPi, to check the value that has been correctly stored. Continue when this works correctly.

As shown, the names of Java variable objects consist of whole words, and use lowercase letters, with multiple words being "separated" by capitalizing the first letter in each word after the first one.

A simplified general form of a Java variable declaration is

   Type IdentifierList ;


When execution reaches such a statement, storage is reserved for each identifier in IdentifierList, and each initializer is evaluated and its value placed in the storage associated with its identifier. An uninitialized identifier is described as undefined, and usually produces a compilation error when used.

In the space below each description, construct an error-free declaration that matches the description:

sum, containing the integer value one:

letter, containing the question-mark character:

average, containing the value 0.0:

done, containing the value false:

Use Express.java to test their correctness, before continuing.

You should now know how to declare variables in Java. In the next experiment, we'll see another kind of declaration.

Back to the Exercise List

Forward to the Next Experiment

Back to the Table of Contents

Back to the Introduction

Copyright 2000 by Prentice Hall. All rights reserved.