Explicitly and Implicitly Converting Between Primitive Types

If at least one grade was entered, line 37 of Fig. 4.10 calculates the average of the grades. Recall from Fig. 4.8 that integer division yields an integer result. Even though variable average is declared as a double, if we had written the averaging calculation as

double average = total / gradeCounter;

it would lose 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.

Most averages are not whole numbers (e.g., 0, -22 and 1024). For this reason, we calculate the class average in this example as a floating-point ...

Get Java™ How To Program (Early Objects), Tenth 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.