Java Reference
In-Depth Information
Table 4-1.
(
continued
)
Operators
Description
Type
Usage
Result
-=
num -= 3
Subtracts 3 from the value of
num
and assigns the result to
num
. If num
is 10, the new value of
num
will be 7.
Arithmetic
compound assignment
Binary
*=
num *= 15
Multiplies 15 to the value of
num
and
assigns the result to
num
. If
num
is 10,
the new value of
num
will be 150.
Arithmetic
compound assignment
Binary
/=
num /= 5
Divides the value of
num
by 5 and
assigns the result to
num
. If
num
is 10,
the new value of
num
will be 2.
Arithmetic
compound assignment
Binary
%=
num %= 5
Calculates the remainder of
num
divided by 5 and assigns the result
to num. If
num
is 12, the new value of
num
will be 2.
Arithmetic
compound assignment
Binary
Addition Operator (+)
The addition operator (+) is used in the form
operand1 + operand2
The addition arithmetic operator (+) is used to add two numeric values represented by the two operands, for
example, 5 + 3 results in 8. The operands may be any numeric literals, numeric variables, numeric expressions, or
method calls. Every expression involving the addition operator has a data type. The data type of the expression is
determined according to one of the four rules:
double
, the other operand is converted to the
double
data type and the whole expression is of type
double
. Otherwise,
•
If one of the operands is the data type
float
, the other operand is converted to the
float
data
type and the whole expression is of type
float
. Otherwise,
•
If one of the operands is the data type
long
, the other operand is converted to the
long
data
type and the whole expression is of type
long
. Otherwise,
•
If one of the operands is the data type
int
, provided they are
•
If none of the above three rules applies, all operands are converted to
not already of type
int
, and the whole expression is of type
int
.
These rules have some important implications. Let's consider a byte variable
b1
, which is assigned a value of 5,
as shown in the following piece of code:
byte b1;
b1 = 5;