Java Reference
In-Depth Information
The variable on the left hand side means “
store
at the memory location
referenced by that variable,” while the variable on the right hand side means
“
get
the value stored at the memory location referenced by that variable.” For
programmer novices, the instruction
x=x+increment;
is quite confusing at first
since it makes no mathematical sense. Let us deconstruct the action taken by
the compiler when encountering such an instruction:
-
Evaluate arithmetic expression
x+increment
:
-
Perform type checking of
increment
with
x
(cast
increment
type if
necessary),
-
Get the value
xVal
stored at memory location referenced by
x
,
-
Get the value
incrementVal
stored at memory location referenced by
increment
,
-
Return the value
xVal+incrementVal
.
-
Finally, store the expression value at memory location referenced by
x
.
Instead of writing
x=x+increment
, we can equivalently write this instruction
compactly using the following shortcut:
x+=increment
Similarly, we can decrement a variable by a given step as follows:
x-=increment
These basic shortcuts extend
9
alsotothe
/
and
∗
operators:
int y=1;
y*=3; // y=3, multiplication assignment
int z=12;
z/=2; // z=6, division assignment
int p=23;
p%=2; // p=1, modulo assignment
1.7.2 Pre-incrementation and post-incrementation
Often we need to add or subtract
one
to (the value of) a variable, say
x
. This
can be done as follows:
x=x+1;
x+=1; // compact form
x=x-1;
x-=1; // compact form
9
These shortcut instructions are, however, rarely used in practice.
Search WWH ::
Custom Search