SEN1001 · Week 2 · Introduction to Java Applications /Elementary Programming

Operators: /, % and precedence

Integer division, the remainder operator and Java's order of operations. Half of the “What is printed?” questions come from here.

integer divisionremainder (modulus)operator precedenceassociativitytype promotioncasting

One of the topics that earns the most points on the midterm. The question type is always the same: “What is printed?”. You run the code in your head and write the output. Anyone who knows the five rules below will not miss these questions:

  1. int / int = int. The fractional part is dropped, there is no rounding: 7 / 2 → 3.
  2. If one side is a double, the result is a double. 7.0 / 2 → 3.5.
  3. % gives the remainder, and the sign of the result is the sign of the left number: -7 % 2 → -1.
  4. * / % first, + - after. Operators at the same level are evaluated left to right.
  5. Parentheses override everything. A (int) cast applies only to the value immediately to its right.

Arithmetic operators

Java has five arithmetic operators. Addition, subtraction and multiplication work the way you know. The two that decide the exam are / and %, because the result changes with the types.

OperatorMeaningint exampledouble example
+addition7 + 2 → 97.0 + 2 → 9.0
-subtraction7 - 2 → 57.5 - 2 → 5.5
*multiplication7 * 2 → 147 * 2.0 → 14.0
/division7 / 2 → 37 / 2.0 → 3.5
%remainder7 % 2 → 15.5 % 2 → 1.5

A double result is printed with .0 even when it is a whole number: 9.0, 14.0. Whether you write 9 or 9.0 in an output question is the difference between points gained and lost.

Division: integer division

When both sides of a division are int, Java computes the quotient and drops everything after the decimal point. This is called integer division. It does not round: 9 / 10 is 0, not 0.9.

System.out.println(7 / 2);    // 3.5 → truncated
System.out.println(9 / 10);   // 0.9 → 0
System.out.println(19 / 5);   // 3.8 → 3 (it would be 4 if it rounded)
System.out.println(-7 / 2);   // -3.5 → truncated toward zero
System.out.println(10 / 5);   // divides exactly
3
0
3
-3
2

Careful with negatives: Java truncates toward zero. -3.5 → -3, not -4. With a negative number too, you just delete the fractional part.

Type promotion

If one side of the division is a double, Java makes the other one a double too and does a real division. What matters is what the types are at the moment the division is done.

System.out.println(7.0 / 2);          // double / int
System.out.println(7 / 2.0);          // int / double
System.out.println((double) 7 / 2);   // cast FIRST: 7.0 / 2
System.out.println((double) (7 / 2)); // parentheses FIRST: 7/2 = 3
double d = 7 / 2;                     // the right side is an int division
System.out.println(d);
3.5
3.5
3.5
3.0
3.0

PITFALL · assigning to a double variable does not save you. In the line double d = 7 / 2; the result is 3.0, not 3.5. The right side is computed first: 7 / 2 is two ints, the result is 3. The fraction is already gone; assigning to a double only adds .0.

Division by zero

System.out.println(5.0 / 0);  // double: does not crash
System.out.println(5 / 0);    // int: the program CRASHES
Infinity
Exception in thread "main" java.lang.ArithmeticException: / by zero

The remainder operator: %

a % b is the number that is left over when you divide a by b. The following equality always holds:

a=(a/b)⋅b+(a % b)example: 17=3⋅5+2a = (a / b)\cdot b + (a \,\%\, b) \qquad \text{example: } 17 = 3\cdot 5 + 2

When computing, think “what is the largest multiple of b that fits into a?” and subtract it from a. 17 % 5: the largest multiple of 5 that fits into 17 is 15, 17 − 15 = 2.

System.out.println(17 % 5);   // 17 = 3*5 + 2
System.out.println(20 % 5);   // divides exactly
System.out.println(3 % 5);    // small % big = itself
System.out.println(-7 % 2);   // the sign is the LEFT one's
System.out.println(7 % -2);   // the left is positive
System.out.println(5.5 % 2);  // works with doubles too
2
0
3
-1
1
1.5

PITFALL · small % big. 3 % 5 is a question where most people write 2 or 0. 5 does not fit into 3 at all. The remainder is 3 itself: 3.

Ready-made tricks with %

What do you want?CodeExample
Is it even?n % 2 == 014 % 2 → 0 → even
Is it odd?n % 2 != 0-7 % 2 → -1 (if you write == 1 you get negatives wrong)
Is it divisible by k?n % k == 021 % 7 → 0
Last digitn % 101234 % 10 → 4
Drop the last digitn / 101234 / 10 → 123
Tens digitn / 10 % 101234 / 10 % 10 → 3
Seconds → minutes + secondss / 60, s % 60125 s → 2 min 5 s
Wrapping on a 12-hour clock(h + k) % 12hour 10 + 5 → 15 % 12 → 3

Method questions such as digit sum, digit count and reversing a number are all built on this two-line pattern:

int n = 1234, sum = 0;
while (n > 0) {
    sum += n % 10;   // take the last digit
    n /= 10;         // drop the last digit
}
System.out.println(sum);
10

Precedence order

When an expression has more than one operator, Java works in the following order. The ones at the top are done first. Operators on the same row are done left to right; only assignment = goes right to left.

RankOperatorsNote
1( )Parentheses are always first.
2x++ x-- ++x --x -x ! (int) (double)Unary operators and casts. A cast applies only to what is immediately to its right.
3* / %All three at the same level, left to right.
4+ -String concatenation + is here too.
5< <= > >=Comparison
6== !=Equality
7&&AND
8||OR
9= += -= *= /= %=Assignment, last, right to left

PITFALL · * / % are at the same level. There is no rule like “multiplication first, then division”. 20 / 4 * 2 goes left to right: 20 / 4 = 5, 5 * 2 = 10. Whoever writes 2.5 gets burned.

Step-by-step solutions

In the exam, solve it like this: at each step process only one operator and rewrite the expression.

7 + 3 % 2 * 5

7 + 3 % 2 * 5     % and * are at the same level, the left one first
7 + 1 * 5
7 + 5
12

1 / 2 * 4.0 versus 4.0 * 1 / 2

1 / 2 * 4.0   →   0 * 4.0   →   0.0      (two ints were divided first)
4.0 * 1 / 2   →   4.0 / 2   →   2.0      (it started with a double)

Same numbers, different order, different result: the types at the moment the division is done are what decide.

(int) 7.9 / 2 versus (int) (7.9 / 2)

(int) 7.9 / 2     →   7 / 2      →   3     (the cast applies only to 7.9)
(int) (7.9 / 2)   →   (int) 3.95 →   3     (truncated, not rounded)

+ with a String

+ does addition between two numbers. The moment one side is a String, it does concatenation. Because it goes left to right, the order changes everything.

System.out.println(1 + 2 + "A");       // (1+2)=3, then "3"+"A"
System.out.println("A" + 1 + 2);       // "A1", then "A12"
System.out.println("A" + (1 + 2));     // parentheses first
System.out.println("Sonuç: " + 5 * 2); // * first
3A
A12
A3
Sonuç: 10

"x" + 5 - 2, on the other hand, does not compile: first it becomes "x5", and then you cannot subtract a number from a String.

Common mistakes

Wrong ideaThe truth
19 / 5 = 4 (rounds)3, Java truncates
-7 / 2 = -4-3, truncated toward zero
3 % 5 = 23, small % big = itself
-7 % 2 = 1-1, the sign comes from the left
double d = 7 / 2; → 3.53.0, the division was done as int
(a + b + c) / 3 is the correct averageWith ints the fraction disappears: write / 3.0
20 / 4 * 2 = 2.510, same level goes left to right
(double) (7 / 2) = 3.53.0, inside the parentheses the int division came first
Odd number: n % 2 == 1With negatives you get -1; write n % 2 != 0

Test yourself

Exam-style questions. Solve them on paper first, then reveal the answer.

Question 1easy

What is printed?

System.out.println(17 / 5 + 17 % 5);
Show answer
5

17 / 5 = 3 (truncated), 17 % 5 = 2, then 3 + 2 = 5.

Question 2medium

What is printed?

System.out.println(2 + 3 * 4 % 5);
Show answer
4

* and % are at the same level, left to right: 3 * 4 = 12, 12 % 5 = 2. Addition last: 2 + 2 = 4.

Question 3medium

What is printed?

double d = 9 / 2;
System.out.println(d);
Show answer
4.0

The right side is two ints: 9 / 2 = 4. Assigned to a double it becomes 4.0. The assignment does not bring back the lost fraction.

Question 4easy

What is printed?

System.out.println((double) 9 / 2);
Show answer
4.5

The cast applies to 9 first: 9.0 / 2 → double division → 4.5.

Question 5medium

What is printed?

System.out.println(-9 % 4);
Show answer
-1

9 = 2·4 + 1. The sign of the remainder comes from the left number (-9): -1.

Question 6medium

What is printed?

System.out.println(10 - 6 / 4 * 2);
Show answer
8

6 / 4 = 1 (truncated), 1 * 2 = 2, 10 - 2 = 8.

Question 7hard

What is printed?

System.out.println(1 + 2 + "3" + 4 + 5);
Show answer
3345

Left to right: 1 + 2 = 3 (a number). 3 + "3" = "33" (now a String). "33" + 4 = "334", + 5 = "3345".

Question 8medium

What is printed?

int n = 4567;
System.out.println(n / 10 % 10);
Show answer
6

Left to right: 4567 / 10 = 456, 456 % 10 = 6. It gives the tens digit.

Question 9medium

What is printed?

System.out.println(7 / 2 * 2.0);
Show answer
6.0

7 / 2 = 3 (two ints). Then 3 * 2.0 = 6.0 (double).

Question 10hard

What is printed?

System.out.println((int) 8.9 / 2 + 8 % 3);
Show answer
6

(int) 8.9 = 8, 8 / 2 = 4. 8 % 3 = 2. 4 + 2 = 6.

Question 11medium

What is the value of a at the end?

int a = 7;
a %= 4;
a *= 3;
a /= 2;
Show answer
4

7 % 4 = 3, 3 * 3 = 9, 9 / 2 = 4 (truncated).

Question 12hard

The code below is meant to print the average. What does it print, and how do you fix it?

int a = 5, b = 2, c = 4;
double avg = (a + b + c) / 3;
System.out.println(avg);
Show answer
3.0

11 / 3 = 3 (int division), which becomes 3.0 when assigned to a double. The fix is / 3.0 or (double) (a + b + c) / 3; then it prints 3.6666666666666665.

Verification: All code examples and answers were run with the JDK (java T.java).

Review card

int / int → int, TRUNCATED (no rounding) 7/2=3 -7/2=-3 9/10=0 one is double → double 7.0/2=3.5 7/2.0=3.5 double d = 7/2; → 3.0 (the division was done as int first) (double)7/2=3.5 but (double)(7/2)=3.0 (int)7.9 = 7 (truncates) (int)7.9/2 = 3 % remainder: 17%5=2 3%5=3 20%5=0 -7%2=-1 (sign from the left) last digit n%10 drop it n/10 tens n/10%10 even n%2==0 PRECEDENCE: () → ++ -- ! cast → * / % → + - → < > → == != → && → || → = same level LEFT TO RIGHT: 20/4*2=10 7+3%2*5=12 "A"+1+2="A12" 1+2+"A"="3A" "A"+(1+2)="A3" 5/0 → ArithmeticException 5.0/0 → Infinity