Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 141
Division and Modulus Operators
ОглавлениеAs we said earlier, the modulus operator, %
, may be new to you. The modulus operator, sometimes called the remainder operator, is simply the remainder when two numbers are divided. For example, 9
divided by 3
divides evenly and has no remainder; therefore, the result of 9 % 3
is 0
. On the other hand, 11
divided by 3
does not divide evenly; therefore, the result of 11 % 3
is 2
.
The following examples illustrate this distinction:
System.out.println(9 / 3); // 3 System.out.println(9 % 3); // 0 System.out.println(10 / 3); // 3 System.out.println(10 % 3); // 1 System.out.println(11 / 3); // 3 System.out.println(11 % 3); // 2 System.out.println(12 / 3); // 4 System.out.println(12 % 3); // 0
As you can see, the division results increase only when the value on the left side goes from 11
to 12
, whereas the modulus remainder value increases by 1
each time the left side is increased until it wraps around to zero. For a given divisor y
, the modulus operation results in a value between 0
and (y - 1)
for positive dividends, or 0
, 1
, 2
in this example.
Be sure to understand the difference between arithmetic division and modulus. For integer values, division results in the floor value of the nearest integer that fulfills the operation, whereas modulus is the remainder value. If you hear the phrase floor value, it just means the value without anything after the decimal point. For example, the floor value is 4
for each of the values 4.0
, 4.5
, and 4.9999999
. Unlike rounding, which we'll cover in Chapter 4, you just take the value before the decimal point, regardless of what is after the decimal point.
The modulus operation is not limited to positive integer values in Java; it may also be applied to negative integers and floating-point numbers. For example, if the divisor is 5, then the modulus value of a negative number is between -4
and 0
. For the exam, though, you are not required to be able to take the modulus of a negative integer or a floating-point number.