Arithmetic Expressions

The arithmetic operators
A class party orders pizza, and a program works out how the slices are shared.
int pizzas = 9;
int slicesEach = 8;
int people = 13;
The expression pizzas * slicesEach is an arithmetic expression. It combines two variables with the multiplication operator, and its value is the int 72. Java has five arithmetic operators: +, -, *, /, and %.
Integer division
Each of the 13 people should get the same number of slices, so the program divides.
System.out.println(72 / 13);
This prints 5. In ordinary arithmetic, 72 divided by 13 is about 5.54, but both operands here are int values, and an operation on two int values gives an int. Java keeps the integer portion of the quotient and drops the rest. It doesn't round: 5.54 is nearer to 6 than to 5, and the result is still 5.
The remainder
The remainder operator gives what's left after the division.
System.out.println(72 % 13);
This prints 7. Five slices for each of 13 people uses 65 slices, and 72 minus 65 leaves 7. The two operators split one division into its whole part and its leftover, so each person gets 5 slices and 7 are left in the boxes. In this course both operands of % are positive.
A double operand
Change one operand to a double and the whole quotient survives.
System.out.println(72 / 13.0);
Because the literal 13.0 is a double, this division produces a double, and the line prints 5.538461538461538. A double value is printed with a decimal point every time, even when it's a whole number. With 12 people, 72 / 12.0 prints 6.0, while 72 / 12 prints 6.
Order of operations
An expression with several operators is a compound expression, and Java groups its values by precedence. Multiplication, division, and remainder go before addition and subtraction. The party gets three extra slices from a smaller box.
System.out.println(pizzas * slicesEach + 3);
System.out.println(pizzas * (slicesEach + 3));
The first line multiplies first, so it prints 75. The parentheses in the second line group slicesEach + 3, which is 11, so it prints 99, the count if every pizza had three more slices.
Operators with equal precedence are evaluated from left to right. In 72 / 13 * 13, the division happens first and gives 5, and then 5 times 13 is 65. The expression doesn't give back 72, since the integer division already dropped the 7 left-over slices.
Dividing by zero
If nobody comes to the party, people is 0, and the expression 72 / people has no integer value at all. An attempt to divide an int by zero results in an ArithmeticException, and the program stops at that expression.