Java provides a rich set of operators to use in manipulating variables. A value used on either side of an operator is called an operand.
For example, in the expression below, the numbers 5 and 8 are operands of the plus operator:
int a = 5 + 8;
Java arithmetic operators:
1. + addition
2. – subtraction
3. * multiplication
4. / division
5. % modulo
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebraic equations.
The + operator adds together two values, such as two constants, a constant and a variable, or a variable and a variable. Here are a few examples of addition:
int a = 40 + 10; int b = a + 34; int c = a + b;
The – operator subtracts one value from another.
int a = 100 - 15; int b = a - 5; int c = a - b;
int a = 100 * 6; int b = a * 3; int c = b * c;
The / operator divides one value by another.
int x = 500 / 5; int y = x / 4; int z = x/ y;
In the example above, the result of the division equation will be a whole number, as int is used as the data type. You can use double to retrieve a value with a decimal point.
The modulo (or remainder) math operation performs an integer division of one value by another, and returns the remainder of that division.
The operator for the modulo operation is the percentage (%) character.
int value = 36; int result = value % 5; // result is 1
Dividing 36 by 5 returns a quotient of 7, with a remainder of 1. Thus, the value of 1 is assigned to the result variable.