Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^118) | Arithmetic Expressions
of the /operator are of type int, so integer division is performed. Dividing 60 by 80 yields the
integer value 0. Next, the machine implicitly converts 0 to the value 0.0 before storing it into
average. The correct (and clear) way to find the average is
average = (double)sum / (double)count;
This statement gives us floating-point division instead of integer division. It results in the
value 0.75 being stored into average.
As a final remark about type conversion and type casting, you may have noticed that we
have concentrated only on the intand doubletypes. It is also possible to stir byte,long,short,
and floatvalues into the pot. The results can be confusing and unexpected. You should
avoid unnecessarily mixing values of these types within an expression. Whenever it be-
comes necessary to do so, you should use explicit type casting to clarify your intentions.


String Conversion Just as Java attempts to convert between numeric types when we mix them


in expressions, so it also tries to convert numeric values to strings when we mix them into
expressions with the string concatenation operator. For instance, if we declare a Stringob-
ject called answer, we can write an assignment expression of the following form:

answer = "The average is: "+ average;

If averagecontains the value 27.65, then the outcome of this assignment is that answercon-
tains the following string:

"The average is: 27.65"

When one of the operands of the +operator is a string and the other operand is a numeric
type, the numeric type is converted to a string prior to concatenation. The +operator has the
same precedence whether it is adding numeric values or concatenating strings. Java’s string
conversion is a useful feature for formatting output in which we mix numeric values with
text that explains their meaning. For example, we might use the preceding expression in a
call to printlnas follows:

System.out.println("The average is: "+ average);

You can use a series of concatenation operators to create complex strings. For example,

answer = "The results are: "+ 27 + 18 + " and "+ 9;

produces the string

"The results are: 2718 and 9"

Notice, however that the values 27 and 18 were concatenated without any spaces between
them. String conversion of numeric values doesn’t add any space around the digits of the
Free download pdf