Math class, random ranges, integer division and casting
Computer Science · AP CSA
Question 1 of 10
0What does the following Java code print? Enter the number printed. int x = 45; int y = 7; int answer = x % y; System.out.println(answer);
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Math class, random ranges, integer division and casting explained
The Math class in Java provides useful methods. Math.random() returns a double that is at least 0.0 and less than 1.0. To get a random whole number from a to b inclusive, multiply Math.random() by the number of possible values, cast the result to an int and add a. The number of whole numbers from a to b inclusive is b - a + 1, and forgetting the + 1 is a common off-by-one error.
Dividing one int by another is integer division: the remainder is discarded, so 7 / 2 gives 3. The remainder operator % gives the leftover, so 7 % 2 gives 1. To keep the decimal part, at least one operand must be a double, such as 7.0 / 2, which gives 3.5.
Casting with (int) truncates towards zero. It does not round, so (int) 3.9 gives 3 and (int) -3.9 gives -3. To round to the nearest whole number, use Math.round, which returns a long, so Math.round(3.5) gives 4.
Worked example
Generate a random whole number from 10 to 20 inclusive.
- The number of possible values is 20 - 10 + 1 = 11.
- Math.random() * 11 gives a value from 0.0 up to, but not including, 11.0.
- Casting with (int) gives 0 to 10.
- Adding 10 gives 10 to 20.
The full expression is (int)(Math.random() * 11) + 10.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
Work out what this code prints and enter it as a number. int n = 29; int d = 3; int q = n % d; System.out.println(q);
Medium
Work out what this code prints and enter it as a number. int a = -55; int b = 4; System.out.println(a / b);
Hard
What value is printed by this Java code? Enter it as a number. int a = 38; int b = 23; double avg = (a + b) / 2.0; System.out.println(avg);