Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.5 Compound Arithmetic Expressions | 117

Arithmetic Expressions So far we have discussed mixing data types across the assignment op-


erator (=). It’s also possible to mix data types within an expression:


someInt * someDouble
4.8 + someInt – 3


Such expressions are called mixed type(or mixed mode) expressions.


Whenever an integer value and a floating-point value are joined by an oper-
ator, implicit type conversion occurs as follows:


1.The integer value is temporarily converted to a floating-point value.
2.The operation is performed.
3.The result is a floating-point value.
Let’s examine how the computer evaluates the expression 4.8+ someInt – 3 , where
someIntcontains the value 2. First, the operands of the +operator have mixed types, so the
value of someIntis converted to 2.0. (This conversion is merely temporary; it does not affect
the value that is currently stored in someInt.) The addition takes place, yielding a value of 6.8.
Next, the subtraction (-) operator joins a floating-point value (6.8) and an integer value (3).
The value 3 is converted to 3.0, the subtraction takes place, and the result is the floating-point
value 3.8.
Just as with assignment statements, you can use explicit type casts within expressions
to lessen the risk of errors. Writing expressions such as


(double)someInt * someDouble
4.8 + (double)(someInt – 3)


makes it clear what your intentions are.
Not only are explicit type casts valuable for code clarity, but in some cases they are
mandatory for correct programming. To see why this is so, given the declarations


int sum;
int count;
doubleaverage;


suppose that sumand countcurrently contain 60 and 80, respectively. Assuming that sumrep-
resents the sum of a group of integer values and countrepresents the number of values, let’s
find the average value:


average = sum / count; // Gives the wrong answer


Unfortunately, this statement stores the value 0.0 into average. Here’s why: The expression
to the right of the assignment operator is not a mixed type expression. Instead, both operands


Mixed type expression An ex-
pression that contains operands
of different data types; also
called a mixed mode expression
Free download pdf