Thursday 14 September 2017

Java Integer Division

Cited from the Book Java How to Program

Dividing two integers results in integer division—any fractional part of the calculation is lost (i.e., truncated).

To cast the results of integer division to floating number, use '(double)' for example.

average = (double) total / gradeCounter;

Java provides the unary cast operator to accomplish this task. The (double) cast operator—a unary operator - to create a temporary floating-point copy of its operand total (which appears to the right of the operator). Using a cast operator in this manner is called explicit conversion or type casting. The value stored in total is still an integer.

The calculation now consists of a floating-point value (the temporary double version of total) divided by the integer gradeCounter. Java knows how to evaluate only arithmetic expressions in which the operands’ types are identical. To ensure that the operands are of the same type, Java performs an operation called promotion (or implicit conversion) on selected operands. For example, in an expression containing values of the types int and double, the int values are promoted to double values for use in the expression. In this example, the value of gradeCounter is promoted to type double, then the floatingpoint division is performed and the result of the calculation is assigned to average. As long as the (double) cast operator is applied to any variable in the calculation, the calculation will yield a double result.

No comments:

Post a Comment