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

 `/*  ReferenceDesigner.com Tutorial for beginners  Arithmetic operators */class arithmetic{  public static void main (String args[]) { int x = 50; int y = 25; int z1,z2,z3,z4,z5; z1 = x + y; z2 = x - y; z3 = x * y; z4 = x/y; z5 = x%y; System.out.println("The value of x + y is " + z1); System.out.println("The value of x - y is " + z2); System.out.println("The value of x * y is " + z3); System.out.println("The value of x / y is " + z4); System.out.println("The value of x % y is " + z5); } }`

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

 `/*  ReferenceDesigner.com Tutorial for beginners  Exercise  */class operator{  public static void main (String args[]) { int x = 12; int y; y= x++%5; System.out.println("The value of i " + x); System.out.println("The value of n " + y);} }`

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

 `/*  ReferenceDesigner.com Tutorial for beginners  Exercise  */class operator1{  public static void main (String args[]) { int x = 50; int y; y = --x*2 ; System.out.println("The value of i " + x); System.out.println("The value of n " + y);} }`

Answer : 98