Numbers: division, casting and overflow
Numbers that surprise you
- Java keeps two kinds of number apart:
int(whole numbers) anddouble(numbers with a decimal point). - The type of the values decides the answer.
7 / 2and7 / 2.0give different results. - Multiple-choice questions test this all the time: integer division,
%, casting, and what happens when anintgets too big.
Integer division and %
- When both values are
int,/gives anint: how many whole times the second fits into the first. The fraction is thrown away, not rounded. %gives the remainder: what is left over.- If either value is a
double, the answer is adouble.

public class Divide {
public static void main(String[] args) {
System.out.println(7 / 2);
System.out.println(7 % 2);
System.out.println(7 / 2.0);
System.out.println(-7 / 2);
int total = 17;
int count = 4;
double average = (double) total / count;
System.out.println(average);
System.out.println((double) (total / count));
}
}
- The output is
3,1,3.5,-3,4.25,4.0. -7 / 2is-3: Java cuts towards zero, it does not round down.(double) total / countcasts first, so the division is adoubledivision.(double) (total / count)divides first, gets4, and only then makes it4.0.
Casting a double to an int
(int) 3.99gives3. The cast cuts off the decimals; it never rounds.- To round a positive number to the nearest whole number, add
0.5first:(int) (x + 0.5). - Java casts an
intto adoubleby itself (double d = 5;is fine), butint n = 3.5;does not compile: you must write the cast.

When an int is too big
- An
intis stored in 32 bits, so it has a largest value,Integer.MAX_VALUE(2147483647), and a smallest,Integer.MIN_VALUE. - Adding 1 to the largest value wraps round to the smallest. This is called overflow. Java shows no error; the answer is simply wrong.

A random whole number in a range
Math.random()returns adoublefrom0.0up to, but not including,1.0.- Multiply by how many values you want, cast to
int, then add the smallest value. - For a dice roll from 1 to 6:
(int) (Math.random() * 6) + 1. Whenmin <= maxand the inclusive range size fits in a positiveint, use(int) (Math.random() * (max - min + 1)) + min.

public class Cast {
public static void main(String[] args) {
double price = 3.99;
int whole = (int) price;
System.out.println(whole);
int rounded = (int) (price + 0.5);
System.out.println(rounded);
int big = Integer.MAX_VALUE;
System.out.println(big);
System.out.println(big + 1);
int roll = (int) (Math.random() * 6) + 1;
System.out.println(roll >= 1 && roll <= 6);
}
}
- The output is
3,4,2147483647,-2147483648, thentrue(the roll is always from 1 to 6).
Common mistakes
| Wrong | Right | Why |
|---|---|---|
double avg = total / count; |
double avg = (double) total / count; |
total / count is int division before the answer is stored |
(double) (total / count) |
(double) total / count |
the cast must happen before the division |
(int) 3.99 is 4 |
(int) 3.99 is 3 |
a cast cuts off the decimals |
(int) Math.random() * 6 + 1 |
(int) (Math.random() * 6) + 1 |
(int) Math.random() is always 0, so the answer is always 1 |
Integer.MAX_VALUE + 1 gives an error |
it gives Integer.MIN_VALUE |
overflow wraps round silently |
Now you try
- Before you run, say what type each expression has:
intordouble. - Press Check answer to test your code.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Complete average(int[] a) so it returns the average of the values as a double, with the decimals kept. The array has at least one value, and the sum of its values fits in an int.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Complete roundToInt(double x). For x of 0 or more, return x rounded to the nearest whole number, with .5 rounding up. Use a cast, not Math.round.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Complete digitSum(int n) for n of 0 or more. Return the sum of its digits: digitSum(4071) es 4 + 0 + 7 + 1 = 12. Use % y /; do not turn the number into a String.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Complete roll(int min, int max) so it returns a random whole number from min hasta max, both included. Assume min <= max and that max - min + 1 fits in a positive int. Use Math.random().
Haz clic en Ejecutar para ver la salida aquí.