Arithmetic expression

An arithmetic expression in Java is analogous to an expression in algebra. Both kinds of expressions contain operators, variables, constants, and parentheses. We’ll introduce Java’s arithmetic operators in this lesson and then use them to write some simple arithmetic expressions.

In Java, we can perform five different operations that involve numeric values: We can add, subtract, multiply, or divide, and find the remainder after division. The operators for these operations are, respectively, +, -, *, /, and %. The variables or constants on which the operators act are called operands. Each of these operators can have two operands, in which case they are called binary operators. However, + and - also can act on a single operand—that is, they can behave as unary operators.

The addition and subtraction operators, + and

As we just mentioned, each of the operators + and - can have either one operand or two operands. We explore these two situations next.

As binary operators

We used the operators + and - in the previous chapter just as we would use them in ordinary addition and subtraction. For the most part, these operators behave as we would expect them to. For example, the statement

int sum = 2 + 3;

assigns 5, the result of adding 2 and 3, to the variable sum. Similarly, the statement

int difference = 8 - 1;

assigns the difference between 8 and 1, or 7, to the variable difference.

When several additions or subtraction operations occur within an expression, the operations occur from left to right in their order of appearance. For example, in the statement

int result = 6 - 9 + 2;

the subtraction occurs before the addition to produce the value –1. If the addition were to occur first, the sum of 9 and 2, when subtracted from 6, would result in – 5. Thus, Java interprets the expression 6 - 9 + 2 as if it were written as (6 - 9) + 2. In fact, Java allows us to use parentheses within an arithmetic expression in much the same way that we use them in an algebraic expression to group operations. For example, note the effect of the following statements:

Get hands-on with 1200+ tech skills courses.