Arithmetic Operators

In this lesson, we will explore the arithmetic operators available in Java.

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:

Press + to interact
public class Example
{
public static void main(String args[])
{
int resultA = 6 - 9 + 2; // resultA is -1
int resultB = (6 - 9) + 2; // resultB is -1
int resultC = 6 - (9 + 2); // resultC is -5
System.out.println(resultA);
System.out.println(resultB);
System.out.println(resultC);
} // End main
} // End Example

Unary operators

When we see values such as +2 and –6 , we likely see a plus sign and a minus sign. In Java, however, literals such as +2 and –6, and expressions such as -sum, use the unary operators + and -. The result of each unary operation is equivalent to a corresponding binary operation that has zero as its first operand. For example, we can view -sum as ...

Access this course and 1400+ top-rated courses and projects.