Explicitly and Implicitly Converting Between Primitive Types

If at least one grade was entered, line 72 of Fig. C.5 calculates the average of the grades. Recall from Fig. C.2 that integer division yields an integer result. Even though variable average is declared as a double (line 45), the calculation

average = total / gradeCounter;

loses the fractional part of the quotient before the result of the division is assigned to average. This occurs because total and gradeCounter are both integers, and integer division yields an integer result. To perform a floating-point calculation with integer values, we must temporarily treat these values as floating-point numbers for use in the calculation. Java provides the unary ...

Get Android™ How to Program, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.