The modulus Operators

By: aathishankaran Printer Friendly Format    

The modulus Operators


            The modulus operator, % returns the remainder of a division operation. It can be applied to floating-point types as well as integer types. (This differs from C/C++, in which the % can only be applied to integer types.) The following example program demonstrates the %:


//Demonstrate the % operator.

class Modulus {

     public static void main ( String args[]) {

          int x = 42;

          double y = 42.25;


          System.out.println(“x mod 10 = “ + x % 10);

System.out.println(“y mod 10 = “ + y % 10);




When you run this program you will get the following output:


            x mod 10 = 2

     y mod 10 = 2.25     


Arithmetic Assignment Operators


            Java provides special operators that can be used to combine an arithmetic operation with an assignment. As you probably know, statements like the following are quite common in programming


     a = a+4;


in java, you can rewrite this statement as shown here.


     a +=4;


This version uses the += assignment operator. Both statements perform the same action: they increase the value of a by 4.


            Here is another example,


     a = a % 2;


Which can be expressed as


            a %= 2;


In this case, the %= obtains the remainder of a/2 and puts that result back into a.


            There are assignment operators provide two benefits. First, they save you a bit of typing, because they are “shorthand” for their equivalent long forms. Second, they are implement more efficiently by the java run-time system than are their equivalent long forms.


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial