Saturday 11 May 2013

Java Modulus Operator

Many programming languages have a modulus operator, which allows you to calculate the remainder left over after a division. If I remember correctly, COBOL actually used the word REMAINDER to allow you to do this. In Java, you use the percent symbol as shown below:

UBUNTU > cat prog26.java
public class prog26
{
public static void main (String args[])
  {
  System.out.println
  ("17/5 = " + (int) 17/5 + " remainder " + 17%3);
  System.out.println
  ("15/2 = " + (int) 15/2 + " remainder " + 15%2);
  }
}
UBUNTU > javac prog26.java
UBUNTU > java prog26
17/5 = 3 remainder 2
15/2 = 7 remainder 1
UBUNTU > 

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.