In some of the earlier lessons, we went over the 4 most used math operators used in Java. Those four included:
Now that we have a little practice underneath our belt in Java, we are going to introduce a new math operator that you’ve probably never seen. This new operator is called: the modulus operator %.
The modulus operator uses division and outputs a result. However, the result is not the dividend. Instead, it is the remainder. In other words, it is the number left over if a number does not divide evenly. Let’s look at an example to better understand.
In Example 1, we can see the equation
9 % 4. As we well know, 9 is not evenly divisible by 4. Therefore, because we are using a modulus operator, we know that 4 goes into 9 twice and leaves us with 1 leftover. Hence, the result for example 1 should be
In Example 2, we have
9 % 3. Knowing that 9 is evenly divisible by 3, we can determine that there will not be a remainder. Therefore, we know that the result for example 2 should be
Let’s take a look at the output below:
Sure enough, we had a remainder of 1 for the first example, and no remainder for the second example.
Although we haven’t seen any opportunities for a modulus operator yet, in future lessons we will see it used with more complex math problems.