Java Reference
In-Depth Information
variables, numbers, operators, and method invocations. An assignment statement
instructs the computer to evaluate (that is, to compute the value of ) the expression
on the right-hand side of the equal sign and to set the value of the variable on the
left-hand side equal to the value of that expression. The following are examples of
Java assignment statements:
totalWeight = oneWeight * numberOfBeans;
temperature = 98.6;
count = count + 2;
The first assignment statement sets the value of totalWeight equal to the number in
the variable oneWeight multiplied by the number in numberOfBeans . (Multiplication is
expressed using the asterisk * in Java.) The second assignment statement sets the value
of temperature to 98.6 . The third assignment statement increases the value of the
variable count by 2 .
Note that a variable may occur on both sides of the assignment operator (both sides
of the equal sign). The assigned statement
count = count + 2;
sets the new value of count equal to the old value of count plus 2 .
The assignment operator when used with variables of a class type requires a bit
more explanation, which we will give in Chapter 4.
Assignment Statements with Primitive Types
An assignment statement with a variable of a primitive type on the left-hand side of the
equal sign causes the following action: First, the expression on the right-hand side of
the equal sign is evaluated, and then the variable on the left-hand side of the equal sign is
set equal to this value.
SYNTAX
Variable = Expression ;
EXAMPLE
distance = rate * time;
count = count + 2;
An assigned statement may be used as an expression that evaluates to a value. When
used this way, the variable on the left-hand side of the equal sign is changed as we have
described, and the new value of the variable is also the value of the assignment expres-
sion. For example,
number = 3;
Search WWH ::




Custom Search