Java Reference
In-Depth Information
// 5.0F is of the type float and 0 is of the type int. 5.0F/0 is of type float.
// Float.POSITIVE_INFINITY is assigned to f1
f1 = 5.0F/0;
// A compile-time error. 5.0F is of the type float and 0.0 is of the type double
// 5.0F/0.0 is of the type double. double to float assignment is not allowed.
f1 = 5.0F/0.0;
f1 = (float)(5.0F/0.0); // f1 is assigned Float.POSITIVE_INFINITY
f1 = 0.0F/0.0F; // Assigns Float.NaN to f1
d1 = 0.0/0.0; // Assigns Double.NaN to d1
d1 = -0.0/0.0; // Assigns Double.NaN to d1
Modulus Operator (%)
The modulus operator (%) is used in the form
operand1 % operand2
The modulus operator is also known as the remainder operator. The modulus operator performs a division
on the left-hand operand by its right-hand operand and returns the remainder of the division, for example, 7%5
evaluates to 2 . All rules about the numeric data conversion of the operands and the determination of the data type
of the expression involving the addition operator are also applicable for expressions involving the modulus operator.
Because the use of the modulus operator involves a division operation, there are some special rules to determine the
result of a modulus operation.
If both operands of the modulus operator are integers, the following rules are applied to compute the result.
Rule #1
It is a runtime error if the right-hand operand is zero. For example,
int num;
num = 15 % 0; // A runtime error
Rule #2
If the right-hand operand is not zero, the sign of the result is the same as the sign of the left-hand operand.
For example,
int num;
num = 15 % 6; // Assigns 3 to num
num = -15 % 6; // Assigns -3 to num
num = 15 % -6; // Assigns 3 to num
num = -15 % -6; // Assigns -3 to num because left-hand operand is -15, which is negative
num = 5 % 7; // Assigns 5 to num
num = 0 % 7; // Assigns 0 to num
If either operand of the modulus operator is a floating-point number, the following rules are applied to compute
the result.
 
Search WWH ::




Custom Search