Hello The Remainder or Modulus Operator in Java

Java has one important arithmetical operator you may not be familiar with, %, also known as the modulus or remainder operator. The % operator returns the remainder of two numbers. For instance 10 % 3 is 1 because 10 divided by 3 leaves a remainder of 1. You can use % just as you might use any other more common operator like + or -.

class Remainder {

  public static void main (String args[]) {

    int i = 10;
    int j = 3;

    System.out.println("i is " + i);
    System.out.println("j is " + j);
  
    int k = i % j;
    System.out.println("i%j is " + k);
  }

}

Here's the output:

% javac Remainder.java
% java Remainder
i is 10
j is 3
i%j is 1

Perhaps surprisingly the remainder operator can be used with floating point values as well. It's surprising because you don't normally think of real number division as producing remainders. However there are rare times when it's useful to ask exactly how many times does 1.5 go into 5.5 and what's left over? The answer is that 1.5 goes into 5.5 three times with one left over, and it's that one which is the result of 5.5 % 1.5 in Java.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 12, 2002