Previous | Home | Next |

The basic arithmetic operators +, –, *, / are used in Java for addition, subtraction, multiplication and division. The / operator denotes integer division if both arguments are integers, and floating-point division otherwise.

The mod function is denoted by %. For example, 19 / 2 is 9, 21 % 2 is 1, and 7.0 / 2 is 3.5.Note that integer division by 0 raises an exception, whereas floating-point division by 0 yields an infinite result.You can use the arithmetic operators in your variable initializations:

int p = 9 int q = 2 * p; // The value of q is 18

There is a convenient shortcut for using binary arithmetic operators in an assignment.

### Example

p += 4; is equal to p = p + 4;

One of the most common operations with a numeric variable is to increment or decrement it value by 1. Java like in C and C++, has both increment and decrement operators: p++ adds 1 to the current value of the variable p, and p-- subtracts 1 from it.

int = 6; p++;

changes p to 7. Because these operators change the value of a variable, they cannot be applied to numbers themselves. For example, 7++ is not a legal statement in java.

There are two forms of these operators, in above examples we have seen the postfix form of the operator that is placed after the operand. There is also a prefix form, ++p. Both change the value of the variable by 1. But there is difference between the two and can only appear when they are used inside expressions. The prefix form does the addition first, the postfix form evaluates to the old value of the variable.

int p = 3; int q = 3; p++; ++q; int x = 4 * p; // x is 12, p is 8 int y = 4 * q; // y is 16, q is 8

Previous | Home | Next |