College Board Unit 1
How it works
Integer division in Java discards the fractional part rather than rounding, and it truncates toward zero, so 7 / 2 is 3 and -7 / 2 is -3. The mod operator % returns the remainder of that division and takes the sign of the left operand, which means -7 % 2 is -1, not 1. Together these two operators power digit extraction, even and odd tests, wrapping values into a range, and index arithmetic.
Use division for how many whole groups fit and modulus for what remains, as when converting minutes into hours and minutes.
Common error
Rounding instead of truncating, and forgetting that a negative operand changes the sign of the remainder.
Worked example
Java
int n = 347;
System.out.println(n / 10);
System.out.println(n % 10);Output
34
7Division removes the last digit of a nonnegative integer; remainder isolates it.
Exercises
1.2.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
System.out.println(-17 / 5);
System.out.println(-17 % 5);Show solution
Output
-3
-2Truncating -3.4 gives -3, and -17 = 5 * (-3) + (-2).
1.2.2 · Write code
Given the nonnegative three-digit integer n = 582, calculate and print the sum of its digits without converting it to a String.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
int n = 582;
int sum = n / 100 + (n / 10) % 10 + n % 10;
System.out.println(sum);