AP Computer Science A · Study guide

Arithmetic Expressions

AP® Computer Science A · Using Objects and Methods

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.

Big Picture

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.

OperatorMeaningint exampledouble example
+Addition7 + 2 → 97.5 + 2 → 9.5
-Subtraction7 - 9 → −27.0 - 2 → 5.0
*Multiplication7 * 2 → 147 * 0.5 → 3.5
/Division7 / 2 → 3 (integer portion only)7 / 2.0 → 3.5
%Remainder7 % 2 → 1Rarely used with doubles
Worked Example 1 Types and values

Evaluating Simple Expressions

Give the value and type of each expression, then check with the program.

Code
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);
Output
4
3
4.75
10.0
5
-2
  1. 119 / 4. Two int values: the integer portion of 4.75, which is 4 (an int).
  2. 219 % 4. 4 goes into 19 four times (16) with 3 left: 3 (an int).
  3. 319 / 4.0. One double: the full quotient 4.75 (a double).
  4. 44 * 2.5. 10.0, a double, which prints with its decimal point even though it is a whole number.
  5. 520 / 4 and 3 - 5. 5 and −2, both int values.
Result: The values are 4, 3, 4.75, 10.0, 5, and −2. The types of the operands decide both the type of the result and whether division keeps the fraction.

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.

Figure 1. An arithmetic operation on two int values produces an int; if at least one operand is a double, the result is a double.
Common Mistake 1 · Expecting the Variable's Type to Change the Arithmetic

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.

Figure 2. With two 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.
Worked Example 2 Averages

Getting the Average Right

Three quiz scores are 9, 8, and 8. Predict each printed average.

Code
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);
Output
8
8.333333333333334
19.666666666666668
  1. 1Line 1. The sum 25 divided by the int 3 is integer division: 8. The fraction is lost.
  2. 2Line 2. Dividing by 3.0 makes it real division: 8.333…, the correct average.
  3. 3Line 3. Without parentheses, only c / 3.0 is divided (2.666…), and then a + b is added: 19.666…, a precedence bug.
  4. 4Rule of thumb. Put the whole sum in parentheses, and make sure at least one operand of the division is a double.
Result: Only line 2 is correct. An average needs both parentheses around the sum and a double in the division.
Common Mistake 2 · Averaging With Integer 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.

Figure 3. The remainder operator turns an ever-growing count into a position in a repeating cycle, such as days of the week, hours on a clock, or seats around a table.
TaskExpressionExample with n = 4729
Last digitn % 109
Remove last digitn / 10472
Even?n % 2 == 0false
Divisible by 3?n % 3 == 0false (4729 = 3 × 1576 + 1)
Whole groups of 12n / 12394
Leftover after groups of 12n % 121
Worked Example 3 Remainder uses

Converting Minutes to Hours and Minutes

A movie lasts 137 minutes. Use / and % to display it as hours and minutes.

Code
int totalMinutes = 137;
int hours = totalMinutes / 60;
int minutes = totalMinutes % 60;
System.out.println(hours + " h " + minutes + " min");
Output
2 h 17 min
  1. 1Whole hours. 137 / 60 is integer division: 2 full hours.
  2. 2Leftover minutes. 137 % 60 is what remains after removing 2 × 60 = 120: 17.
  3. 3Check. 2 × 60 + 17 = 137, so nothing was lost.
  4. 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.
Result: The movie is 2 h 17 min. Integer division and remainder used together split a quantity into whole units and leftovers.
Worked Example 4 Digits

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.

Code
int n = 4729;
System.out.println(n % 10);
System.out.println(n / 10);
System.out.println((n / 10) % 10);
System.out.println(n % 2);
Output
9
472
2
1
  1. 1Last digit. Dividing by 10 leaves a remainder equal to the ones digit: 4729 % 10 is 9.
  2. 2Drop the last digit. 4729 / 10 is 472; integer division discards the 9.
  3. 3Tens digit. Drop the last digit, then take the new last digit: 472 % 10 is 2.
  4. 4Even or odd. n % 2 is 0 for even numbers and 1 for odd ones; 4729 is odd.
Result: The results are 9, 472, 2, and 1. Combining / 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.

Figure 4. Multiplication, division, and remainder have precedence over addition and subtraction, and operators with the same precedence are evaluated from left to right.
PrecedenceOperatorsGrouping
HighestParentheses ( )Innermost first
Next* / %Left to right
Lowest of these+ -Left to right
Worked Example 5 Precedence

Evaluating a Compound Expression

Evaluate 2 + 3 * 4 % 5 - 6 / 4 by hand, then with parentheses added as (2 + 3) * 4 % 5 - 6 / 4.

Code
System.out.println(2 + 3 * 4 % 5 - 6 / 4);
System.out.println((2 + 3) * 4 % 5 - 6 / 4);
Output
3
-1
  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.)
  2. 2With parentheses. (2 + 3) = 5 first. Then 5 * 4 = 20, 20 % 5 = 0, 6 / 4 = 1. Finally 0 − 1 = −1.
  3. 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.
Result: The first expression is 3; the parenthesized version is −1. Parentheses change which values are grouped together, and therefore the answer.
Common Mistake 3 · Doing Additions First Because They Appear First

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.

Worked Example 6 Exceptions

Dividing an Integer by Zero

A program computes points per game. Predict what happens when no games have been played.

Code
int points = 45;
int games = 0;
System.out.println("Computing...");
System.out.println(points / games);
  1. 1Compile time. The code is valid, so it compiles.
  2. 2Run time. "Computing..." prints, then 45 / 0 divides an integer by the integer zero, which throws an ArithmeticException and stops the program.
  3. 3Prevention. Check that the divisor is not zero before dividing, a pattern written with an if statement.
Result: The program prints "Computing..." and then stops with an ArithmeticException. Integer division by zero is a run-time error.
Common Mistake 4 · Assuming Integer Results Are Rounded

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.

Core Synthesis

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.