Arithmetic Expressions
How Java computes with numbers: the five arithmetic operators, why int and double results differ, integer division and the remainder operator, operator precedence, and the one arithmetic operation that stops a program.
Arithmetic expressions combine numeric values, variables, and operators to compute new values. Java has five arithmetic operators: +, -, *, /, and %. The rules that trip people up are about types: an operation on two int values produces an int, so dividing two integers keeps only the integer portion of the quotient, while an operation involving at least one double produces a double. Combined with operator precedence, these rules let you predict the exact value of any arithmetic expression.
1Arithmetic Expressions
An arithmetic expression consists of numeric values, variables, and operators, and it evaluates to a single number. price * quantity, (a + b) / 2.0, and total % 7 are all arithmetic expressions. Expressions can appear anywhere a value is needed: on the right side of an assignment, inside a println, or as part of a larger expression.
Every expression has a type as well as a value. The arithmetic expressions here are of type int or double, and the type is determined by the operands, not by where the result will be stored. Assigning 7 / 2 to a double variable still produces 3.0, because the division was performed with two integers before the value was stored.
| Operator | Meaning | int example | double example |
|---|---|---|---|
+ | Addition | 7 + 2 → 9 | 7.5 + 2 → 9.5 |
- | Subtraction | 7 - 9 → −2 | 7.0 - 2 → 5.0 |
* | Multiplication | 7 * 2 → 14 | 7 * 0.5 → 3.5 |
/ | Division | 7 / 2 → 3 (integer portion only) | 7 / 2.0 → 3.5 |
% | Remainder | 7 % 2 → 1 | Rarely used with doubles |
Evaluating Simple Expressions
Give the value and type of each expression, then check with the program.
System.out.println(19 / 4);
System.out.println(19 % 4);
System.out.println(19 / 4.0);
System.out.println(4 * 2.5);
System.out.println(20 / 4);
System.out.println(3 - 5);
4
3
4.75
10.0
5
-2
- 1
19 / 4. Twointvalues: the integer portion of 4.75, which is 4 (anint). - 2
19 % 4. 4 goes into 19 four times (16) with 3 left: 3 (anint). - 3
19 / 4.0. Onedouble: the full quotient 4.75 (adouble). - 4
4 * 2.5. 10.0, adouble, which prints with its decimal point even though it is a whole number. - 5
20 / 4and3 - 5. 5 and −2, bothintvalues.
2int Results and double Results
An arithmetic operation that uses two int values evaluates to an int value. An arithmetic operation that uses at least one double value evaluates to a double value. When one operand is an int and the other a double, Java automatically converts (widens) the int to a double and then performs the operation.
The rule applies to each operation separately, in the order the expression is evaluated. In 1 / 2 + 0.5, the division happens first with two integers, giving 0, and only then is 0.5 added, giving 0.5. In 1 / 2.0 + 0.5, the division already involves a double, giving 0.5, and the final result is 1.0. When an expression mixes types, evaluate it one operation at a time and track the type at every step.
int values produces an int; if at least one operand is a double, the result is a double.double ratio = 3 / 4; stores 0.0, not 0.75. The division 3 / 4 is computed first, with two int values, producing 0; only then is 0 widened to 0.0 for storage. To get 0.75, make an operand a double: 3.0 / 4.
3Integer Division
When dividing numeric values that are both int values, the result is only the integer portion of the quotient. Any fractional part is discarded, not rounded: 19 / 4 is 4, even though 4.75 is closer to 5. When at least one value is a double, the result is the full quotient.
Integer division is not a bug; it is exactly what you want when counting whole groups. How many full boxes of 12 can be packed from 50 eggs? 50 / 12 is 4. How many complete hours are in 137 minutes? 137 / 60 is 2. The danger comes only when you wanted a real-number answer, such as an average, and forgot that both operands were integers.
int values, division gives only the whole number of groups and the remainder operator gives what is left over. With a double, division gives the exact quotient.Getting the Average Right
Three quiz scores are 9, 8, and 8. Predict each printed average.
int a = 9;
int b = 8;
int c = 8;
System.out.println((a + b + c) / 3);
System.out.println((a + b + c) / 3.0);
System.out.println(a + b + c / 3.0);
8
8.333333333333334
19.666666666666668
- 1Line 1. The sum 25 divided by the
int3 is integer division: 8. The fraction is lost. - 2Line 2. Dividing by
3.0makes it real division: 8.333…, the correct average. - 3Line 3. Without parentheses, only
c / 3.0is divided (2.666…), and thena + bis added: 19.666…, a precedence bug. - 4Rule of thumb. Put the whole sum in parentheses, and make sure at least one operand of the division is a
double.
double in the division.(a + b + c) / 3 with int values discards the fraction of the average. Write (a + b + c) / 3.0. Also keep the parentheses: without them, only the last value is divided, which is a precedence error rather than a type error.
4The Remainder Operator
The remainder operator % computes the remainder when one number a is divided by another number b. 17 % 5 is 2, because 5 goes into 17 three times (15) with 2 left over. Here a is never negative and b is always positive, so the remainder is always between 0 and b − 1.
That last fact makes % surprisingly useful. Because n % b always falls between 0 and b − 1, it can wrap a count around a cycle: (day + 10) % 7 gives a day of the week, and hour % 12 gives a position on a clock face. It also answers divisibility questions: n % 2 == 0 tests for even numbers, and n % 10 extracts the last digit. Paired with integer division by the same number, % splits a quantity into whole units and leftovers.
| Task | Expression | Example with n = 4729 |
|---|---|---|
| Last digit | n % 10 | 9 |
| Remove last digit | n / 10 | 472 |
| Even? | n % 2 == 0 | false |
| Divisible by 3? | n % 3 == 0 | false (4729 = 3 × 1576 + 1) |
| Whole groups of 12 | n / 12 | 394 |
| Leftover after groups of 12 | n % 12 | 1 |
Converting Minutes to Hours and Minutes
A movie lasts 137 minutes. Use / and % to display it as hours and minutes.
int totalMinutes = 137;
int hours = totalMinutes / 60;
int minutes = totalMinutes % 60;
System.out.println(hours + " h " + minutes + " min");
2 h 17 min
- 1Whole hours.
137 / 60is integer division: 2 full hours. - 2Leftover minutes.
137 % 60is what remains after removing 2 × 60 = 120: 17. - 3Check. 2 × 60 + 17 = 137, so nothing was lost.
- 4The pattern.
/by a unit size counts complete units;%by the same size gives the remainder. It works for seconds and minutes, cents and dollars, or inches and feet.
2 h 17 min. Integer division and remainder used together split a quantity into whole units and leftovers.Pulling Digits Out of a Number
For the number 4729, use % and / to find the last digit, the number without its last digit, and the tens digit.
int n = 4729;
System.out.println(n % 10);
System.out.println(n / 10);
System.out.println((n / 10) % 10);
System.out.println(n % 2);
9
472
2
1
- 1Last digit. Dividing by 10 leaves a remainder equal to the ones digit:
4729 % 10is 9. - 2Drop the last digit.
4729 / 10is 472; integer division discards the 9. - 3Tens digit. Drop the last digit, then take the new last digit:
472 % 10is 2. - 4Even or odd.
n % 2is 0 for even numbers and 1 for odd ones; 4729 is odd.
/ 10 and % 10 lets a program examine a number one digit at a time.5Operator Precedence
Operators can be combined to build compound expressions. At compile time, numeric values are associated with operators according to operator precedence, which determines how they are grouped. Multiplication, division, and remainder have precedence over addition and subtraction. Operators with the same precedence are evaluated from left to right. Parentheses override precedence: whatever is inside them is grouped first.
To evaluate a compound expression by hand, first handle anything in parentheses, then make one pass from left to right performing *, /, and %, then a second pass from left to right performing + and -. Rewrite the expression after every single operation, as in Figure 4; it is slower than doing it in your head and far less error-prone.
Left-to-right order matters even among operators of equal precedence. 12 / 3 * 2 is (12 / 3) * 2 = 8, not 12 / (3 * 2) = 2. When in doubt, or when an expression would be hard for a reader to follow, add parentheses; they cost nothing and make the intended grouping explicit.
| Precedence | Operators | Grouping |
|---|---|---|
| Highest | Parentheses ( ) | Innermost first |
| Next | * / % | Left to right |
| Lowest of these | + - | Left to right |
Evaluating a Compound Expression
Evaluate 2 + 3 * 4 % 5 - 6 / 4 by hand, then with parentheses added as (2 + 3) * 4 % 5 - 6 / 4.
System.out.println(2 + 3 * 4 % 5 - 6 / 4);
System.out.println((2 + 3) * 4 % 5 - 6 / 4);
3
-1
- 1Without extra parentheses. Evaluate
*,/,%left to right: 3 * 4 = 12, 12 % 5 = 2, 6 / 4 = 1. Then+and-left to right: 2 + 2 = 4, 4 − 1 = 3. (Figure 4 shows each step.) - 2With parentheses. (2 + 3) = 5 first. Then 5 * 4 = 20, 20 % 5 = 0, 6 / 4 = 1. Finally 0 − 1 = −1.
- 3Grouping happens at compile time. The compiler decides how operators group by precedence before the program runs; the values are then computed in that grouping.
In 10 + 6 / 2, the division happens first even though the addition is written first: the answer is 13, not 8. Precedence, not reading order, decides grouping; reading order only breaks ties between operators of the same precedence.
6Division by Zero
An attempt to divide an integer by the integer zero results in an ArithmeticException, a run-time error that stops the program. The same applies to the remainder operator with a zero divisor. The compiler cannot catch this in general, because the divisor is often a variable whose value is known only while the program runs.
The fix is to make sure the divisor cannot be zero before dividing, typically by checking it with an if statement and handling the zero case separately, for example by printing a message instead of an average when no scores have been entered.
Dividing an Integer by Zero
A program computes points per game. Predict what happens when no games have been played.
int points = 45;
int games = 0;
System.out.println("Computing...");
System.out.println(points / games);
- 1Compile time. The code is valid, so it compiles.
- 2Run time. "Computing..." prints, then
45 / 0divides an integer by the integer zero, which throws anArithmeticExceptionand stops the program. - 3Prevention. Check that the divisor is not zero before dividing, a pattern written with an
ifstatement.
ArithmeticException. Integer division by zero is a run-time error.Integer division truncates: it chops off the fractional part. 29 / 10 is 2, not 3, even though 2.9 is closer to 3. If a rounded result is needed, compute with double values and round deliberately.
Four Habits for Arithmetic Expressions
1. Track the Type at Every Step
int with int stays int; any double makes the result double.
2. Integer Division Truncates
It counts whole groups; use % for what is left over.
3. Multiply Before You Add
*, /, % group before + and −; ties go left to right.
4. Guard Every Divisor
Integer division by zero throws an ArithmeticException.
Arithmetic expressions consist of numeric values, variables, and the operators +, -, *, /, and %, and include expressions of type int and double. An operation on two int values evaluates to an int; an operation with at least one double evaluates to a double. Dividing two integers keeps only the integer portion of the quotient, and % computes the remainder. Operator precedence groups multiplication, division, and remainder before addition and subtraction, with ties evaluated left to right and parentheses overriding both. Dividing an integer by the integer zero results in an ArithmeticException.