Example 1
(a) (int) 5.7 + 8.9 =} 5 + 8.9 =} 13.9 ( a double value)
(b) (int) 5.7 + (int) 8.9 =} 5 + 8 =} 13 (an int value)
(c) (int) (5.7 + 8.9) =} (drrt ) (14.6)=}14 (an int value)
(d) (double) (1/2) =} (double) a=} 0.0 (a double value)
(e) (double) 5/0 =} 5. a/a (produces positive infinity)
(f) (double) (5/0) (throws an ArithmeticException)
We can use the print or println methods to print values of expressions,
with or without accompanying strings. In using arithmetic expressions
as parts of the argument to print or println, we must be careful of
the fact that the operator + has different meanings for string expressions
(where it means concatenation) and numerical expressions (where it means
addition). 1 Whichever way we use +, it has the same precedence as the
arithmetic operator and if there is more than one occurrence of + in an
expression, evaluation takes place from left to right unless parentheses are
used to alter the order of evaluation. If + is used between a string and a
primitive value, the primitive value is automatically converted to a string
and then the two strings are concatenated. Using these rules, Java forms
a single string argument for print or println and then prints this string.
The next example illustrates the use of + in a variety of contexts.
|