Java TUTORIAL - Arithmetic operator
There are five arithmetic operators in Java + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).
Arithmetic Operators
Operator | Meaning |
+ | Add two numbers |
- | subtract two numbers |
* | multiply two numbers |
/ | divide two numbers |
% | modulo of two numbers |
Most of this is straightforward. The % operator called modulo operator returns the remainder. So x%y means remainder when x is divided by y.
|
If you compile and run this program, you will get the output as follows
C:\Program Files\Java\jdk1.7.0_17\bin>java arithmetic The value of x + y is 75 The value of x - y is 25 The value of x * y is 1250 The value of x / y is 2 The value of x % y is 0 |
Combining the increment and decrement operators (++ and --) needs special considerations. Depending upon the whether we use pre increment ( decrement) or post increment ( decrement) operators the value on the right hand side of the assignment operation is assigned before or after the operation. Take a look at this example which also illustrated the usage of the modulo operator %.
|
In the assignment statement
y= x++%5;
the value of x in incremented AFTER the assignment statement. So the value y is printed in this case as 2. However, if we had written the assignment statement as
y= ++x%5;
the value of y would have been 3. In this case the value of x is incremented and then the modulo operation takes place.
Exercise
What is the value of y printed in the following code
|
Answer : 98