Java evaluates *, / and % before + and -, and works left to right through operators of equal precedence. When both operands are int, / gives an int that drops any fractional part, so 7 / 2 is 3, and % gives the remainder, so 7 % 2 is 1. If either operand is a double, that operation is done in double, so 7 / 2.0 is 3.5.
Quick check
A variable is declared as double d = 4; What does System.out.println(d); print?Show answerHide answer
4.0. A
doubleprints with a decimal point.In ordinary math, what is 2 + 3 × 4?Show answerHide answer
- Multiplication comes before addition, so it is 2 + 12.
Know these already? Jump to the practice questions
What you'll be able to do
- Calculate the value of a Java expression using precedence and left-to-right order.
- Determine the result of
intdivision and%, including negative operands. - Predict whether each step of a mixed expression is done in
intordouble. - Use
%and/to test for even numbers, split off digits and wrap a value around. - Identify when a division throws an
ArithmeticException.
Key terms
Integer division
Division where both operands are int; the result is an int with the fractional part removed, truncated toward zero.
- In plain English
- Divide, then chop off everything after the decimal point.
- Don't write
- "
intdivision rounds to the nearest whole number."
Remainder operator
The operator %: a % b gives what is left over after int division of a by b, with the sign of a.
- In plain English
- The leftover after sharing
ainto groups ofb. - Don't write
- "
a % bgives the percentage ofathatbis."
Precedence
The rule that decides which operator in an expression is applied first.
- In plain English
- The order of operations Java follows.
- Don't write
- "Java always works strictly left to right."
In what order does Java evaluate an expression?
Parentheses come first. Then *, / and %, which share one precedence level, are applied left to right. Then + and -, which share a lower level, are applied left to right. Learn this: operators and precedence, like all Java syntax, are not on the Java Quick Reference.
| Expression | Order of work | Value |
|---|---|---|
10 - 4 / 2 * 3 | 4 / 2 = 2, 2 * 3 = 6, 10 − 6 | 4 |
20 / 4 * 2 | 20 / 4 = 5, then 5 * 2 | 10 |
(10 - 4) / 2 * 3 | 6 / 2 = 3, then 3 * 3 | 9 |
In the second row, / and * are equal, so the leftmost goes first: the answer is 10, not 2.5.
Check yourself
Show answerHide answer
- 6 / 3 = 2, then 2 * 2 = 4, then 18 − 4 = 14.
What does / do when both operands are int?
It gives an int, keeping only the whole-number part of the true quotient. The part after the decimal point is dropped, not rounded, and the result moves toward zero:
7 / 2is 3, and19 / 10is 1.-7 / 2is -3, not -4.2 / 5is 0, because 0.4 truncates to 0.
Dividing an int by zero, with / or %, throws an ArithmeticException when the code runs, so the program stops at that line.
int d = 0;
int q = 10 / d; // throws ArithmeticException
Key idea
With two int operands, / truncates toward zero; it never rounds.
Check yourself
Show answerHide answer
-2. The true quotient is −2.25, and truncating toward zero gives −2.
What does % give, and what is it for?
a % b is the remainder after int division: 17 % 5 is 2, because 17 = 3 × 5 + 2. If 0 ≤ a < b, the remainder is a itself, so 4 % 7 is 4. The result takes the sign of the left operand: -7 % 2 is -1.
Three common uses:
| Use | Expression | Example |
|---|---|---|
| Even test | n % 2 == 0 | 538 % 2 is 0, so 538 is even |
| Last digit and the rest | n % 10, n / 10 | 538 % 10 is 8; 538 / 10 is 53 |
| Wrap around | (h + k) % 24 | (22 + 5) % 24 is 3 |
The wrap works because % 24 always lands in 0 to 23 for non-negative values, like hours on a clock.
Check yourself
Show answerHide answer
- 100 = 14 × 7 + 2.
What happens when int and double mix?
Java decides the type one operation at a time. If either operand of an operator is a double, the int is converted and that operation gives a double. If both are int, it gives an int.
7 / 2.0is 3.5.4.0 * 1 / 2is 2.0:4.0 * 1is 4.0, then 4.0 / 2 is 2.0.1 / 2 * 4.0is 0.0:1 / 2is 0 inint, before thedoubleappears.
Storing an int result in a double comes too late to save the fraction: double r = 7 / 2; gives r the value 3.0.
Check yourself
Show answerHide answer
0.0. 3 / 4 is the int 0, and 0 * 2.0 is 0.0.
Worked example 1: Evaluate an expression by hand
Question: What value does r hold after int r = 17 % 5 * 2 + 9 / 4 - 3; runs?
What tells you the method
One expression with several operators: apply precedence, then left to right within each level.
Step 1: Do the
*,/and%level, left to right.Operation Value 17 % 52 2 * 24 9 / 42 Why%,*and/share the higher level, and9 / 4truncates 2.25 to 2.Step 2: Do the
+and-level, left to right.4 + 2 = 6, then 6 − 3 = 3.
WhyAddition and subtraction share the lower level.
Check it
Insert the parentheses Java uses: ((17 % 5) * 2) + (9 / 4) - 3 = 4 + 2 − 3 = 3.
Answer
3
Worked example 2: Split a number into digits
Question: What is printed when this code segment runs?
int n = 472;
int ones = n % 10;
n = n / 10;
int tens = n % 10;
n = n / 10;
System.out.println(ones + tens + n);
What tells you the method
% 10 and / 10 on the same variable: trace it with a table, because n changes between lines.
Step 1: Trace each line.
Line nonestens1 472 2 472 2 3 47 2 4 47 2 7 5 4 2 7 Why% 10reads the last digit;/ 10drops it, so the next% 10reads the digit before.Step 2: Add the three values.
2 + 7 + 4 = 13.
WhyAll three are
int, so+adds them.
Check it
The digits of 472 are 4, 7 and 2, and 4 + 7 + 2 = 13.
Answer
13
Worked example 3: Choose an expression for an average
Question: int total = 7; and int count = 2; are declared. Which expression evaluates to the average, 3.5?
- A)
1.0 * total / count - B)
total / count - C)
total / count * 1.0 - D)
1.0 * (total / count)
What tells you the method
A mixed-type choice: evaluate each option one operation at a time, noting the type at each step.
Step 1: Evaluate A.
1.0 * totalis 7.0, then 7.0 / 2 is 3.5.WhyThe
doubleappears before the division, so the division is done indouble.Step 2: Evaluate B, C and D.
B is 3. C is 3 * 1.0 = 3.0. D works out
total / countfirst, giving 3, then 3.0.WhyIn B, C and D the
intdivision happens first and drops the 0.5.
Check it
A is 7.0 / 2 and 2 × 3.5 = 7.0, so A is exact.
Answer
A
Your turn
Question: What is printed when this code segment runs?
int totalMinutes = 135;
int hours = totalMinutes / 60;
int minutes = totalMinutes % 60;
System.out.print(hours);
System.out.print(" h ");
System.out.println(minutes);
Step 1: Work out
hours.135 / 60 is 2.25 as a true quotient, so
intdivision gives 2.Step 2: Your go: work out
minutesand the printed line.
Show the full solutionHide the solution
Step 2. 135 = 2 × 60 + 15, so minutes is 15. The three print calls give 2, then " h ", then 15.
Answer: 2 h 15
Traps
Trap
int division rounds to the nearest whole number.
It seems right because rounding is what you do with decimals in math. But Java truncates toward zero, so 19 / 10 is 1 and -7 / 2 is -3.
What is the value of 29 / 10?
2, because 2.9 is truncated, not rounded.
Trap
Storing the result in a double keeps the fraction.
It seems right because a double can hold 3.5. But in double avg = 7 / 2; the int division runs first and gives 3; only then is 3 stored, as 3.0.
What value does avg hold after double avg = 9 / 2;?
4.0. 9 / 2 is the int 4, stored as 4.0.
Trap
% always gives a result from 0 up.
It seems right because remainders in math are never negative. But in Java the result takes the sign of the left operand, so -7 % 3 is -1.
What is the value of -10 % 3?
-1. -10 / 3 is -3, and −10 − (−3 × 3) = −1.
What's examined
On the AP® Computer Science A exam, Unit 1 expressions appear in multiple-choice questions that ask for a value or printed output, so check each option for a precedence slip, rounding instead of truncating, or an int division done too early. In free response, / and % turn up inside the methods you write.
Practice questions
- Recall What is the value of
23 % 6?
Show answer
Answer: 5
Marking points:
- 23 = 3 × 6 + 5, so the remainder is 5.
- Apply What is the value of
2 + 14 / 4 * 3 - 1?
- A) 2
- B) 10
- C) 11
- D) 11.5
Show answer
Answer: B. 14 / 4 = 3, then 3 * 3 = 9, then 2 + 9 − 1 = 10.
Why the others are wrong:
- A works out 4 * 3 first, ignoring left-to-right order: 14 / 12 = 1.
- C adds 2 + 14 first, ignoring precedence: 16 / 4 * 3 − 1 = 11.
- D uses true division, 14 / 4 = 3.5, which
intdivision never gives.
- Apply What is printed when this code segment runs?
int a = -17;
System.out.println(a / 5);
System.out.println(a % 5);
Show answer
Answer: -3 then -2, one per line.
Marking points:
- −17 / 5 is −3.4, truncated toward zero to −3.
- −17 = −3 × 5 + (−2), so the remainder is −2, with the sign of −17.
- Exam-style What is printed when this code segment runs?
int x = 9;
double y = x / 2;
double z = x / 2.0;
System.out.println(y + z);
- A)
8 - B)
8.0 - C)
8.5 - D)
9.0
Show answer
Answer: C. y is 4.0, because x / 2 is the int 4; z is 4.5; 4.0 + 4.5 is 8.5.
Why the others are wrong:
- A treats both divisions as
intand forgets that adoubleprints with a decimal point. - B treats
x / 2.0asintdivision too. - D assumes storing
x / 2in adoublekeeps the 0.5.
- Exam-style This code segment is meant to print the sum of the digits of 538, which is 16. Give the number of the line that stops it working.
1: int n = 538;
2: int ones = n % 10;
3: int tens = n / 10 % 10;
4: int hundreds = n % 100;
5: System.out.println(ones + tens + hundreds);
Show answer
Answer: Line 4.
Marking points:
- Line 3 is correct: 538 / 10 is 53, and 53 % 10 is 3.
- Line 4 gives 538 % 100 = 38, the last two digits, so the code prints 8 + 3 + 38 = 49.
- Changing line 4 to
n / 100gives 5, and 8 + 3 + 5 = 16.
- Exam-style Which expression is
trueexactly when theintvariablenis odd, for everyintvalue ofn?
- A)
n % 2 == 1 - B)
n % 2 == 0 - C)
n / 2 == 1 - D)
n % 2 != 0
Show answer
Answer: D. An odd n leaves a remainder of 1 or −1, and an even n leaves 0, so "not 0" catches every odd value.
Why the others are wrong:
- A misses negative odd numbers:
-3 % 2is -1, not 1. - B is
truefor even numbers. - C uses division instead of the remainder, so it is
trueonly for 2 and 3.
- Apply Days are numbered 0 to 6. What value does
dayhold after this code segment runs?
int day = 5;
day = (day + 10) % 7;
Show answer
Answer: 1
Marking points:
- 5 + 10 = 15, and 15 = 2 × 7 + 1, so
daywraps around to 1.
- Recall Name the exception thrown when an
intis divided by anintvariable that holds 0.
Show answer
Answer: ArithmeticException
Marking points:
intdivision or remainder by zero has no value, so Java throws anArithmeticExceptionwhen that line runs.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Parentheses first, then
*,/and%left to right, then+and-left to right. intdivided byinttruncates toward zero:-7 / 2is -3.%gives the remainder, with the sign of the left operand.- Each operation is
doubleonly if one of its own operands is adouble; an earlierintdivision has already lost the fraction. - An
intdivision or remainder by zero throws anArithmeticException.