By LearnAllStudents Editorial Team. Source check dates are listed below.
Follow the worked example
In Java, int total = 7 and int n = 2. double a = total / n evaluates integer division first and stores 3.0.
double b = (double) total / n evaluates 7.0 ÷ 2 and stores 3.5.
double c = (double) (total / n) again stores 3.0 because the cast occurs after division.
Place the listing inside a Java class. Try the worked example’s inputs from its main method.
static double[] compareDivision(int total, int n) {
if (n == 0) {
throw new IllegalArgumentException("The divisor must be nonzero.");
}
double a = total / n;
double b = (double) total / n;
double c = (double) (total / n);
return new double[] { a, b, c };
}Check the operand types before the division
Java chooses integer division when both operands are integers. If one operand is a double, the other is converted and division can retain a fraction. A cast around the whole quotient happens after that decision.
Try it yourself
Evaluate 5 / 2 + 1.0 and 5 / 2.0 + 1.
Check your reasoning
The first is 3.0 because integer division gives 2. The second is 3.5.
Use the idea in a different situation
Why does 100 × correct / total risk losing a fractional percentage when all values are int?
Check the second task
Both multiplication and division use int arithmetic when written in Java with *, so cast before division to keep the fraction.
For parents
Ask, “Which changes the result: casting one number first or casting the quotient at the end?”
They should explain why (double) 7 / 2 is 3.5 and (double) (7 / 2) is 3.0.
Write the intermediate result above the division sign and ask which expression Java evaluates first.
How a tutor would approach this
Write down the expected output or state before running the Java code. Compare it with the actual output, trace where they first differ and test the fix against another input that arrives at the same kind of boundary.
Frequently asked questions
What mistake should I look for first?
The destination type says how the result is stored. It does not retroactively change the operators used to get it.
How can I use this with a longer practice set?
Read the current course framework and official sample questions before deciding how to practise this technique in an exam-length task.
Are these official past-paper questions?
The worked example and practice tasks here are original. The sources section links to the official material for your course.
How can I tell if I can use the method on a new question?
Try the second task with the worked example covered. Explain which step needs to change and why before checking the answer.
Official sources
- College Board AP Computer Science A course and exam description (checked 2026-11-26)
Related pages
Try a free 30-minute demo
Work through a question with a tutor. No payment needed.
Request a free 30-minute demo