Java Reference
In-Depth Information
Notice that a variable declaration, like a statement, ends with a semicolon. These
declarations can appear anywhere a statement can occur. The declaration indicates
the type and the name of the variable. Remember that the name of each primitive
type is a keyword in Java ( int , double , char , boolean ). We've used the keyword
double to define the type of these three variables.
Once a variable is declared, Java sets aside a memory location to store its value.
However, with the simple form of variable declaration used in our program, Java does
not store initial values in these memory locations. We refer to these as uninitialized
variables, and they are similar to blank cells in a spreadsheet:
height ?
weight ?
bmi ?
So how do we get values into those cells? The easiest way to do so is using an
assignment statement. The general syntax of the assignment statement is
<variable> = <expression>;
as in
height = 70;
This statement stores the value 70 in the memory location for the variable height ,
indicating that this person is 70 inches tall (5 feet 10 inches). We often use the phrase
“gets” or “is assigned” when reading a statement like this, as in “ height gets 70 ”or
height is assigned 70 .”
When the statement executes, the computer first evaluates the expression on the
right side; then, it stores the result in the memory location for the given variable. In
this case the expression is just a simple literal value, so after the computer executes
this statement, the memory looks like this:
height 70.0
weight ?
bmi ?
Notice that the value is stored as 70.0 because the variable is of type double . The
variable height has now been initialized, but the variables weight and bmi are still
uninitialized. The second assignment statement gives a value to weight :
weight = 195;
After executing this statement, the memory looks like this:
height 70.0
weight 195.0
bmi ?
The third assignment statement includes a formula (an expression to be evaluated):
bmi = weight / (height * height) * 703;
 
Search WWH ::




Custom Search