Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^120) | Arithmetic Expressions
The first two + operators are integer additions because neither of their operands are
strings. Only the last+operation is a concatenation; its left operand is the sum of the
three numbers, which it converts into a string. If a chain of+operators begins with a con-
catenation, then the succeeding operators are concatenations as well. The following is an
invalid assignment:
answer = 27 + 18 + 9; // Invalid; expression type is int
String conversion occurs only with the concatenation operator, not with assignment. The re-
sult of this expression is an intvalue, which can’t be assigned to a string. However, we can
use a trick to turn this expression into a series of string concatenations. That is, we can con-
catenate the values with the empty string:
answer = "" + 27 + 18 + 9; // Valid; expression is a String
The value stored in answeris then "27189". But what if we want answerto contain the
string representing the sum of these integers? That is, how do we get Java to first compute
the integer sum before applying string conversion? We do so in the same way that we change
the order of evaluation of any expression: We use parentheses.
answer = "" + (27 + 18 + 9);
Now the expression 27 + 18 + 9 is evaluated first and, because all of the operands are integers,
the +operators perform addition. Once the sum is computed, it is converted to a string and
concatenated with the empty string. The assignment then stores "54"into answer.
To summarize, Java’s string conversion is a useful feature for formatting numeric out-
put. But keep in mind that it works only as part of string concatenation. Also, remember
that you must consider the precedence rules whenever you write a complex expression con-
taining multiple numeric values.


3.6 Additional Mathematical Methods


Certain computations, such as taking square roots or finding the absolute value of a number,
are very common in programming. It would be an enormous waste of time if every program-
mer had to start from scratch and create methods to perform these tasks. To help make the
programmer’s life easier, Java’sMathclass provides a number of useful methods, shown in
Table 3.1. Note that the class name must precede each of these methods with a dot in between.

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf