Skip to main content
Logo image

Section 2.3 Arithmetic expressions

Earlier in this unit we saw how variables, such as score, can be used to name a place we store a value and also how we can write literal values like 42 in our programs. Both variables and literal values are simple kinds of expressions.
We also learned in SectionΒ 2.1Β Values and variables how data types are defined by both by set of values they can represent and the set of operators that can operate on those values. Now we are going to see how we can use operators to create more complex expressions that compute new values from other expressions.

Subsection 2.3.1 Basic arithmetic

To take a simple example, 2 + 3 is an expression consisting of the two literal values 2 and 3 and the operator +. The values are sometimes called the operands of the expression. The + operator works in Java about how you expect, adding together its two operands and producing a new value, in this case 5. The expression 2 + 3 is an example of an arithmetic expression, an expressions consisting of numeric values being operated on by one of Java’s arithmetic operators.
Java uses the standard mathematical operators for addition (+), subtraction (-), and division (/). The multiplication operator is written as *, as it is in most programming languages, since the character sets used until relatively recently didn’t have a character for a real multiplication sign, Γ—, and keyboards still don’t have a key for it. For similar reasons the Γ· symbol is not used in Java.
Just like variables have a type that was determined when we declared it, expressions have a type that is determined by the kind of value they produce. Arithmetic expressions can be of type int or double depending on the types of the values in the expression.
An arithmetic expression consisting only of int values will always evaluate to an int value, even if the true mathematical result is not an integer. But an arithmetic expression that contains at least one double value will always evaluate to a double value.
This means that when if we divide two ints, we will get an int result and the decimal part of the result will be thrown away. So, for instance, 5 / 2 would give us 2, not 2.5. This is called truncating division. If we want to preserve the part after the decimal point we need a double result, so we should make at least one of the values in the expression a double like 2.0. The expression 5 / 2.0 will give us 2.5.

Activity 2.3.1. Basic arithmetic operators.

Run the code below to see the four basic arithmetic operators in action. Do all of those operators do what you expected? What about 2 / 3? Isn’t it surprising that it prints 0? See the note above about truncating division with integers. Change the code to make it print the decimal part of the division too. You can do this by making at least one of the numbers a double like 2.0.

Subsection 2.3.2 The remainder operator

Java also supports a fifth arithmetic operator, %, called the remainder operator. Like the other four basic arithmetic operators it takes two operands. Mathematically it returns the remainder after dividing the first number by the second, using truncating division. For instance, 5 % 2 evaluates to 1 since 2 goes into 5 two times with a remainder of 1.
While you may not have heard of remainder as an operator, think back to elementary school math when you first learned long division, before you learned about decimals. You probably learned how to give the answer to a long division that didn’t divide evenly in terms of the number of even divisions and the remainder. The remainder is what is returned by the % operator. In the figures below, the remainders are the same values that would be returned by 2 % 3 and 5 % 2.
Figure 2.3.1. Long division showing the integer result and the remainder
Sometimes peopleβ€”including Professor Lewis in the next videoβ€”will call % the modulo, or mod, operator. That is not actually correct though the difference between remainder and modulo only matters when the signs of the operands differ. (The difference has to do with what kind of division is done before finding the remainder; the remainder operator is based on truncating integer division where the quotient is truncated toward zero while modulo is based on Euclidean division which truncates toward negative infinity.) With operands of the same sign, remainder and modulo give the same results. Java does have a method Math.floorMod in the Math class if you need to use modulo instead of remainder, but % is all you need in the AP exam and it will only be used with positive operands.
Here’s the video.

Activity 2.3.2.

In the example below, try to guess what it will print out and then run it to see if you are right.

Note 2.3.2.

Remember that the value of x % y when x is smaller than y is always x. Since y can’t go into x at all (goes in 0 times), the result is just x. So 2 % 3 is 2 since 2 < 3.

Activity 2.3.3.

What is the result of 158 % 10?
  • This would be the result of 158 divided by 10. % gives you the remainder.
  • % gives you the remainder after the division.
  • When you divide 158 by 10 you get a remainder of 8.

Activity 2.3.4.

What is the result of 3 % 8?
  • 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number!
  • This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8.
  • What is the remainder after you divide 3 by 8?

Subsection 2.3.3 Math bugs

While computers are pretty good at math they will only do what we tell them. And sometimes what we tell them isn’t exactly what we wanted. For instance, we can get bit by an unexpected truncating division if we divide two ints when we really wanted a double result.
And sometimes it’s something as silly as using the wrong operator. For example, when the Hubble Space Telescope was launched to space in 1990, a bug where a programmer subtracted when they should have added (or possibly the other way around) caused it to point in the wrong direction! It missed its target stars by about half a degree which is about the width of the moon seen from Earth. Thorough testing is the only way to make sure there are no logic errors that will cause runtime errors in your code. Try the following example that tries to convert centimeters to inches. Can you fix the runtime error?

Activity 2.3.5. Fix the math bug.

The following code is trying to convert centimeters to inches, but it has a math error. Run the code to see that there are no error messages, but it simply does the wrong calculation! Can you fix the logic error in the code? Note that one inch is equivalent to 2.54 cms.
Another kind of math bug is when we ask Java to do something mathematically impossible. The main one we need to know about is what happens when we divide by zero, something that is not defined in math. In an int expression, dividing by zero will result in an ArithmeticException , as we saw in the SectionΒ 1.2Β Debugging and being stuck. Try it in one of the active codes to see what happens.

Note 2.3.3.

In double expressions, dividing by zero is not an error. Instead we get a special double value Infinity which might makes sense to you if you’ve learned about limits in math class. But if not, don’t worry about it; it’s not part of the AP exam.

Subsection 2.3.4 Compound expressions

Each arithmetic operator operates on just two operands. So what does an expression like 2 * 3 + 4 mean? If we remember our PEMDAS, we know in regular math that this expression should evaluate to 10 since we first multiply 2 times 3, getting 6, and then add 4 to that, getting 10. It works the same in Java. Java evaluates the * operator with the two operands are 2 and 3, and then the + operator with the value of the subexpression 2 * 3 and 4.
This kind of expression, where one or both of the operands are also arithmetic expressions, not just variables or a literal values, is called a compound expression.
When compound expressions are evaluated, Java uses operator precedence rules, just like we do in regular math. So the expression 2 + 5 * 3 is 17, not 21 because the expression 5 * 3 is evaluated first and then becomes one of the operands to the + operator.
In Java, multiplication *, division /, and remainder % are done before addition + and subtraction -. However, as under PEMDAS rules, anything in parentheses is done first. It doesn’t hurt to put in extra parentheses if you are unsure as to what will be done first or just to make it more clear.

Activity 2.3.6. Compound expressions.

In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider operator precedence. How do the parentheses change the precedence?

Subsection 2.3.5 Coding Challenge: Pay calculator

In this coding challenge, you can work in pairs to create a pay calculator using math expressions and operators.

Project 2.3.7. Pay calculator.

Complete the following expressions for a pay calculator.

Subsection 2.3.6 Summary

  • (AP 1.3.C.1) Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
  • (AP 1.3.C.2) The arithmetic operators consist of +, -, * , /, and % also known as addition, subtraction, multiplication, division, and remainder.
  • (AP 1.3.C.2) An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away.
  • (AP 1.3.C.2) An arithmetic operation that uses at least one double value will evaluate to a double value.
  • (AP 1.3.C.3) When dividing numeric values that are both int values, the result is only the integer portion of the quotient. Anything after the decimal point is thrown away. When dividing numeric values that use at least one double value, the result is the double quotient as expected.
  • (AP 1.3.C.4) The remainder (modulo) operator % is used to compute the remainder when one number is divided by another number.
  • (AP 1.3.C.5) Multiple operators can be used to combine expressions into compound expressions.
  • (AP 1.3.C.5) During evaluation, numeric values are associated with operators according to operator precedence to determine how they are grouped. *, /, % have precedence over + and -, unless parentheses are used to group those to be evaluated first. Operators with the same precedence are evaluated from left to right.
  • (AP 1.3.C.6) An attempt to divide an integer by zero will result in an ArithmeticException.

Subsection 2.3.7 AP Practice

Activity 2.3.8. Compound expression practice.

Consider the following code segment.
System.out.println(5 + 5 / 2 * 3 - 1);
What is printed when the code segment is executed?
  • 0.666666666666667
  • Don’t forget that division and multiplication will be done first due to operator precedence.
  • Don’t forget that division and multiplication will be done first due to operator precedence.
  • Yes, this is equivalent to (5 + ((5 / 2) * 3) - 1).
  • Don’t forget that division and multiplication will be done first due to operator precedence, and that an int/int gives an int truncated result where everything to the right of the decimal point is dropped.
  • Don’t forget that division and multiplication will be done first due to operator precedence.
You have attempted of activities on this page.