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.

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Arithmetic operators
  4.  */
  5. class arithmetic{
  6.  
  7. public static void main (String args[]) {
  8. int x = 50;
  9. int y = 25;
  10. int z1,z2,z3,z4,z5;
  11. z1 = x + y;
  12. z2 = x - y;
  13. z3 = x * y;
  14. z4 = x/y;
  15. z5 = x%y;
  16. System.out.println("The value of x + y is " + z1);
  17. System.out.println("The value of x - y is " + z2);
  18. System.out.println("The value of x * y is " + z3);
  19. System.out.println("The value of x / y is " + z4);
  20. System.out.println("The value of x % y is " + z5);
  21.  
  22. }
  23.  
  24. }


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 %.

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Exercise
  4.  */
  5. class operator{
  6.  
  7. public static void main (String args[]) {
  8. int x = 12;
  9. int y;
  10. y= x++%5;
  11. System.out.println("The value of i " + x);
  12. System.out.println("The value of n " + y);
  13. }
  14.  
  15. }


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

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Exercise
  4.  */
  5. class operator1{
  6.  
  7. public static void main (String args[]) {
  8. int x = 50;
  9. int y;
  10. y = --x*2 ;
  11. System.out.println("The value of i " + x);
  12. System.out.println("The value of n " + y);
  13. }
  14.  
  15. }


Answer : 98