Java integer-double division confusion

In your first example:

int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!

sum is an int, and 4 is also an int. Java is dividing one integer by another and getting an integer result. This all happens before it assigns the value to double avg, and by then you’ve already lost all information to the right of the decimal point.

Try some casting.

int sum = 30;
double avg = (double) sum / 4; // result is 7.5

OR

int sum = 30;
double avg = sum / 4.0d; // result is 7.5

Leave a Comment