Java Reference
In-Depth Information
Note that an assignment is different from initialization in a declaration. Initialization causes a variable to
have the value of the constant that you specify when it is created. An assignment involves copying data
from one place in memory to another. For the assignment statement above, the compiler will have
allocated some memory (4 bytes) to store the constant
777
as type
int
. This value will then be copied
to the variable
c
. The value in
c
will be extracted and copied to
b
. Finally the value in
b
will be copied
to
a
. (However, strictly speaking, the compiler may optimize these assignments when it compiles the
code to reduce the inefficiency of performing successive assignments of the same value in the way I
have described.)
With simple assignments of a constant value to a variable of type
short
or
byte
, the constant will be
stored as the type of the variable on the left of the
=
, rather than type
int
. For example:
short value = 0;
value = 10;
This declaration, when compiled and run, will allocate space for the variable
value
, and arrange for its
initial value to be
0
. The assignment operation needs to have
10
available as an integer literal of type
short
, occupying 2 bytes, because
value
is of type
short
. The value
10
will then be copied to the
variable
value
.
Now let's look in more detail at how we can perform calculations with integers.
Integer Calculations
The basic operators you can use on integers are
+
,
-
,
*
, and
/
, which have the usual meanings - add,
subtract, multiply, and divide, respectively. Each of these is a binary operator; that is, they combine two
operands to produce a result,
2
+
3
for example. An operand is a value to which an operator is applied.
The priority or precedence that applies when an expression using these operators is evaluated is the
same as you learnt at school. Multiplication and division are executed before any addition or
subtraction operations, so the expression:
20 - 3*3 - 9/3
will produce the value
8
, since it is equivalent to
20
-
9
-
3
.
As you will also have learnt in school, you can use parentheses in arithmetic calculations to change the
sequence of operations. Expressions within parentheses are always evaluated first, starting with the
innermost when they are nested. Therefore the expression:
(20 - 3)*(3 - 9)/3
is equivalent to
17*(-6)/3
which results in
-34
.
Of course, you use these operators with variables that store integer values as well as integer literals. You
could calculate a value for
area
of type
int
from values stored in the variables
length
and
breadth
,
also of type
int
, by writing:
area = length * breadth;