Java Reference
In-Depth Information
x
4 bytes
main memory
FIGURE 2.5: Allocating integer in main memory.
a double from the keyboard. Note that when we call a method, we can specify additional
parameters inside the parentheses. However, even if no additional information is included,
we still need to type the opening and closing parenthesis. This tells Java that we are calling
a method and not simply referring to a variable.
Next, let us concentrate on the third step of the algorithm. The variable y is created
and its value computed. Here is a possible implementation of the step.
double y;
double c = 9/5;
y=32+c x;
Note that multiplication in Java is denoted by the character “*”, while division is denoted
by the character “/”. This is standard for most programming languages. The second line
of code calculates the value of the coecient by which we will multiply the temperature in
Celsius. Note that the command does two things: it declares the variable c as a double (i.e.,
a real number with double precision) and it sets the value of c .Notethateveryvariablemust
be declared before it can be referenced. It is also the case that every variable can be defined
only once. The third line sets the value of y . Note that Java allows arbitrary arithmetic
expressions. Since multiplication has higher priority than addition, the multiplication of c
and x will be done first and then the number 32 will be added, Conversely, if we wanted
the addition to be done first, we could have used braces as follows.
y=(32+c) x;
Since parentheses have the highest precedence, the addition will be performed first and
then the multiplication.
It is worthwhile to examine the assignment operator (a.k.a., =) in greater details. The
left-hand side must always be a variable. Writing the following code simply does not make
sense.
3=x;
The right-hand side can be an expression that evaluates to a value. Of course, the type of
this value must be compatible with the type of the left-hand-side variable. The assignment
operator actually returns a value. This means that you can write Java code as shown below.
x=y=z =4 ;
This code will be executed from right to left. First, z will become equal to 4. The
expression z = 4 will return the new value of z , that is, the number 4. Next, y will become
equal to 4 and the assignment operator will return the new value of the variable y ,thatis,
4. Lastly, x will become equal to 4.

Search WWH ::

Custom Search