Java Reference
In-Depth Information
The program begins the same way, setting the three variables to the following
values and reporting this initial value for BMI:
height 70.0
weight 195.0
bmi 27.976530612244897
But the new program then includes the following assignment statement:
weight = 180;
This changes the value of the weight variable:
height 70.0
weight 180.0
bmi 27.976530612244897
You might think that this would also change the value of the bmi variable. After
all, earlier in the program we said that the following should be true:
bmi = weight / (height * height) * 703;
This is a place where the spreadsheet analogy is not as accurate. A spreadsheet can
store formulas in its cells and when you update one cell it can cause the values in
other cells to be updated. The same is not true in Java.
You might also be misled by the use of an equals sign for assignment. Don't con-
fuse this statement with a statement of equality. The assignment statement does not
represent an algebraic relationship. In algebra, you might say
x
=
y
+
2
In mathematics you state definitively that x is equal to y plus two, a fact that is true
now and forever. If x changes, y will change accordingly, and vice versa. Java's
assignment statement is very different.
The assignment statement is a command to perform an action at a particular point
in time. It does not represent a lasting relationship between variables. That's why we
usually say “gets” or “is assigned” rather than saying “equals” when we read assign-
ment statements.
Getting back to the program, resetting the variable called weight does not reset
the variable called bmi . To recompute bmi based on the new value for weight ,we
must include the second assignment statement:
weight = 180;
bmi = weight / (height * height) * 703;
Otherwise, the variable bmi would store the same value as before. That would be a
rather depressing outcome to report to someone who's just lost 15 pounds. By includ-
ing both of these statements, we reset both the weight and bmi variables so that
memory looks like this:
height 70.0
weight 180.0
bmi 25.82448979591837
 
Search WWH ::




Custom Search