Casting

From double to int
A weather app stores the day's high temperature as a double, and its large display shows whole degrees.
double high = 23.6;
int shown = (int) high;
The cast (int) is a type name in parentheses, written in front of a value. It produces the int 23, which is stored in shown. The variable high isn't changed and still holds 23.6.
The cast keeps 23 and throws away the .6. It doesn't round, even though 23.6 is closer to 24. Leave the cast out and Java refuses the line. A conversion from double to int can lose information, so Java makes the program ask for it every time, even for a value like 23.0.
Truncation goes toward zero, and on a negative value that means up. Overnight the temperature changed by -2.7 degrees.
double change = -2.7;
int wholeChange = (int) change;
The cast drops the .7 and keeps the sign, so wholeChange holds -2, not -3.
Where a cast applies
A cast applies to the one value right after it, and it's applied before multiplication or division. Rain falls at 2.5 millimeters an hour for 3 hours, and the app shows the total in whole millimeters.
double rate = 2.5;
int hours = 3;
System.out.println((int) rate * hours);
System.out.println((int) (rate * hours));
The first line prints 6. The cast applies to rate alone and turns 2.5 into 2, and then 2 times 3 is 6.
The second line prints 7. The parentheses make the multiplication happen first, so the cast gets the product 7.5 and truncates it to 7. Casting the total keeps more of the rain than casting the rate, because the rate's fraction is lost three times over.
Rounding to the nearest integer
Java's Quick Reference for this course has no rounding method, so a rounded value is built from a cast. For a value that isn't negative, add 0.5 and then truncate.
int nearest = (int) (high + 0.5);
Here 23.6 + 0.5 is 24.1, and truncating gives 24, the integer closest to 23.6. A value whose fractional part is under .5 stays below the next integer after the 0.5 is added. One at .5 or more reaches it.
A negative value takes the mirror image: subtract 0.5, then truncate.
int nearestChange = (int) (change - 0.5);
Here -2.7 - 0.5 is -3.2, which truncates to -3, the integer closest to -2.7. Adding 0.5 instead gives -2.2, and that truncates to -2.
In both expressions the parentheses around the sum are needed. Without them, (int) high + 0.5 casts high alone, giving 23, and then adds 0.5 to get the double 23.5. An int variable won't take that, so the statement doesn't compile.