Arithmetic and integer division
What you'll learn:
- predict the result of integer division and of the remainder, negative numbers included;
- convert a number from one type to another and know when a
(int)cast is needed; - notice
intoverflow and guard against it; - join strings with numbers and print numbers by a template with
String.format.
Java counts like a calculator, but this calculator has its own rules. The main one: it remembers the type of every number, whole or fractional.
The +, - and * operators work on whole numbers the way school arithmetic does. Division is different: if both numbers are int, the result is an int too, and an int has no fractional part.
Picture handing out sweets to children. You can't cut a sweet, so each child gets a whole number of them, and the leftovers stay with you. Division of whole numbers works the same way:
public class Main {
public static void main(String[] args) {
int sweets = 17;
int kids = 5;
System.out.println(sweets / kids); // 3
System.out.println(sweets % kids); // 2
}
}Let's see what the program printed:
sweets / kidsprints3: seventeen sweets for five children is three each. The/operator gave the quotient.sweets % kidsprints2: two sweets stayed with you. The%operator gave the remainder.
An ordinary calculator would show 3.4, but the program printed 3. The sweets picture works well for positive numbers. For negative ones Java has its own rule, covered in the section on the remainder.
Five operators
Java has five arithmetic operators:
+—addition;-—subtraction;*—multiplication;/—division;%—the remainder of a division.
The order of operations is the one from school: *, / and % run before + and -, and operators of the same level run left to right. So 2 + 3 * 4 is 14, while (2 + 3) * 4 is 20: parentheses change the order.
Integer division
Dividing one whole number by another is called integer division: the fractional part of the result is dropped, not rounded.
17 / 5is3, although on paper it comes out as3.4.19 / 5is3too, although3.8is closer to four.-17 / 5is-3, not-4: a negative result loses its fraction as well.
So integer division always moves the result toward zero: a positive one down, a negative one up.
You get a fraction when at least one of the two numbers is fractional. 7.0 / 2 and 7 / 2.0 give 3.5: a number with a decimal point has the type double, and the division becomes the ordinary one.
The remainder and its sign
The remainder is what is left after integer division. The % operator gives it, and a rule ties it to the quotient: a / b * b + a % b always equals a.
That rule fixes the sign of the remainder. It matches the sign of the dividend, that is, the left number:
System.out.println(-17 / 5); // -3
System.out.println(-17 % 5); // -2
System.out.println(17 % -5); // 2Let's go through the lines:
-17 / 5prints-3: the fraction is dropped toward zero.-17 % 5prints-2. The quotient is-3, and-3 * 5gives-15. Reaching-17takes another-2, and that is the remainder.17 % -5prints2. The dividend17is positive, so the remainder is positive too, even though the divisor is negative.
Interviewers like to ask this: what is the sign of the remainder when the dividend is negative? In math the remainder is usually taken as non-negative, but in Java it takes the sign of the dividend.
Division by zero
What happens when you divide by zero depends on the type of the numbers:
int boxes = 0;
System.out.println(12.0 / boxes); // Infinity
System.out.println(12 / boxes);Exception in thread "main" java.lang.ArithmeticException: / by zeroFractional division: Infinity
12.0 / boxes is a fractional division, and Java does not treat it as an error. The result is a special double value, infinity, and the program prints Infinity.
Integer division: an exception
12 / boxes has no result. The program stops at this line and prints the message above. An error that happens while a program runs is called an exception, and ArithmeticException is its name.
Even a division by a literal, such as 12 / 0, is no error to the compiler: the program compiles, and the exception happens when it runs.
Common mistake
The result of dividing two int values is stored in a double in the hope of getting a fraction:
public class Main {
public static void main(String[] args) {
int total = 5;
int count = 2;
double average = total / count; // ✗
System.out.println(average); // 2.0
}
}The compiler sees no error, and the program prints 2.0. Java first runs total / count as integer division and gets 2. Only then does that 2 become 2.0 to fit into the double. To get 2.5, one of the numbers must be fractional before the division: for example, declare total as a double.
Key points
- Dividing two whole numbers drops the fraction:
17 / 5is3, and-17 / 5is-3. - The
%operator gives the remainder, and its sign matches the dividend:-17 % 5is-2. - You get a fraction only when at least one of the numbers is fractional before the division.
- Integer division by zero throws an
ArithmeticException, while fractional division givesInfinity.