Before explaining Java modulus to calculate remainders, let’s have a look at some very basic mathematical concepts about division and remainders. It may seem trivial to discuss such basic mathematical concepts, but believe me, there are some Java programmers who have difficulty understanding these very basic mathematical concepts. So, let us get started.

java-modulus-to-calculate-remainders

What are Remainders?

As the word implies, a remainder is something that remains. For example, if you have one dozen sweets, and you want to give 5 sweets to each of your children, how many sweets will remain? So, 5 sweets to the first child and 5 sweets to the second child make a total of 10 sweets. You started with a dozen, that is 12 sweets, so you still have 2 sweets left with you. These two sweets remain, so 2 is the remainder in this case.

Mathematically speaking, 12 divided by 5 leaves a remainder of 2. Similarly, 36 divided by 10 leaves a remainder of 6.

Java Modulus to Calculate Remainders

Java has an arithmetical operator known as modulus or remainder operator. This Java modulus is denoted by the (%) sign. Let us see the examples presented in the previous section.

12 % 5 = 2

Explanation: when 12 is divided by 5, it leaves 2 as a remainder. As shown in the example of children and sweets, you can give 5 sweets to two children, and you will be left with 2 sweets.

36 % 10 = 6

Explanation: when you divide 36 with 10, the remainder is 6. This is because when 10 is multiplied by 3, it gives the answer of 30. Now, you cannot multiply 10 with four, because it equals 40, which is greater than 36.

Surprisingly, Java modulus can be used with floating point values as well. It means that java remainder operator can be used with fractional values like 1.6 and 9.5. For example 9.5 % 1.6 = 1.5