Java Reference
In-Depth Information
Initializing a Variable in a Declaration
You can combine the declaration of a variable with an assignment statement that gives the
variable a value.
SYNTAX
Type
Variable_1
=
Expression__1
,
Variable_2
=
Expression__2
,
...
;
Some of the variables may have no equal sign and no expression, as in the first example.
EXAMPLE
int
numberReceived = 0, lastNumber, numberOfStations = 5;
double
speed = 98.9, distance = speed * 10;
char
initial = 'J';
More Assignment Statements
★
There is a shorthand notation that combines the assignment operator (
=
) and an
arithmetic operator so that a given variable can have its value changed by adding, sub-
tracting, multiplying, or dividing by a specified value. The general form is
Variable
Op
=
Expression
which is equivalent to
Variable
=
Variable
Op
(
Expression
)
The
Expression
can be another variable, a constant, or a more complicated arith-
metic expression. The
Op
can be any of
+
,
−
,
*
,
/
,
%
, as well as some operators we have
not yet discussed. The operator % has not yet been discussed but is explained later in
this chapter. (A full list of values for
Op
can be seen at the bottom of the precedence
table in Appendix 2.) Below are examples:
EXAMPLE:
EQUIVALENT TO:
count += 2;
count = count + 2;
total -= discount;
total = total - discount;
bonus *= 2;
bonus = bonus * 2;
time /= rushFactor;
time = time / rushFactor;
change %= 100;
change = change % 100;
amount *= count1 + count2;
amount = amount * (count1 + count2);