Java Reference
In-Depth Information
int
toa
float
orfroma
long
toa
double
cancausealossofprecision.(See
The CERT
®
cision when converting primitive integers to floating-point
,
” for more details.)
Theseconversionscanoccurwhenusingmultiplicativeoperators(
%
,
*
,
/
),additiveop-
erators (
+
,
-
), comparison operators (
<
,
>
,
<=
,
>=
), equality operators (
==
,
!=
), and integer
bitwise operators (
&
,
|
,
^
).
Examples
In the following example,
a
is promoted to a
double
before the
+
operator is applied:
int a = some_value;
double b = some_other_value;
double c = a + b;
In the following program fragment,
b
is first converted to
int
so that the
+
operator
can be applied to operands of the same type:
int a = some_value;
char b = some_character;
if ((a + b) > 1.1f) {
// Do something
}
Theresultof
(a+b)
isthenconvertedtoa
float
,andthecomparisonoperatorisfinally
applied.
Compound Operators
Typecoercionmayoccurwhencompoundexpressionsareusedwithmixedoperandtypes.
Examples of compound assignment operators are
+=
,
-=
,
*=
,
/=
,
&=
,
^=
,
%=
,
<<=
,
>>=
,
>>>=
, and
|=
.
According to the JLS §15.26.2, “Compound Assignment Operators” [JLS 2013],