Java Reference
In-Depth Information
The order of precedence is important, but if you have to think about it, you are
either writing or reading code that will be hard to maintain. Rather than rely on the
order of precedence conventions, always make your intentions explicit by using
parentheses.
Unlike COBOL, Java always uses arithmetic symbols instead of words for its
math operations. For example, the assignment operator is an equals sign (=) in-
stead of MOVE, or x - y instead of COBOL's SUBTRACT Y FROM X. Math oper-
ations in Java always use a syntax similar to COBOL's COMPUTE verb.
B INARY A RITHMETIC O PERATIONS
Binary operations (that is, operations involving two operators) come in several
types: arithmetic, conditional, relational, assignment, and bitwise. You will explore
the various arithmetic operations here.
Integer operations always create a result type of int , unless one of the operands
is of type long , in which case the result type is long . If x in the preceding example
had been defined as a short , then you would have had to cast the result into a short
in order to avoid a compiler error.
short x;
x = (short) (2 + 7 * 3); // x = 23
Likewise, floating-point operations always create a result of type double unless
both operands are of type float . Remember that floating-point constants by default
are of type double . Further, the compiler can automatically convert either an inte-
ger or a float into a double, but converting a double into either of these requires a
cast. Similarly, integers will automatically convert to floats, but floats won't convert
to integers unless you cast them.
int i;
float f;
double d;
d = f + 1.2; // OK
f = f + 1.2; // not good, cast required
f = (float) (f + 1.2); // OK
f = f + 1.2F; // also OK
i = (int) f; // OK, but possible precision loss
f = (float) (d + 1.2); // OK, but possible precision loss
d = f + i; // OK
Search WWH ::




Custom Search