TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
% operator in Java is the arithmetic remainder operator. It evaluates the remainder of dividing the left-hand operand (dividend) by the right-hand operand (divisor). While frequently referred to as the modulo operator, Java’s implementation strictly calculates the remainder via truncated division. This means the sign of the resulting value is determined entirely by the dividend, ignoring the sign of the divisor.
Operand Compatibility
The% operator accepts all primitive numeric types, including integer types (byte, short, char, int, long) and floating-point types (float, double). It also accepts their corresponding object wrapper classes (e.g., Integer, Double) via automatic unboxing. Standard binary numeric promotion applies to the operands before the operation is executed.
Integer Remainder Mechanics
For integer operands, the% operator satisfies the following identity, which the Java Language Specification guarantees will hold true even if the division operation overflows:
(a / b) * b + (a % b) == a
Because Java uses truncated division (rounding towards zero), the remainder inherits the sign of the left-hand operand (a).
Floating-Point Remainder Mechanics
Unlike C and C++, Java permits the% operator on floating-point operands. The operation computes a truncating remainder analogous to the integer remainder operator. The result is calculated as a - (b * q), where q is the integer portion of a / b truncated toward zero.
The % operator explicitly does not compute the IEEE 754 remainder, which uses a rounding division (round to nearest). To achieve true IEEE 754 remainder behavior in Java, developers must use Math.IEEEremainder().
Edge Cases and Exceptions
The behavior of the% operator changes significantly depending on whether the operands are integers or floating-point numbers when encountering zero or infinite values.
Integer Exceptions:
- Division by Zero: If the right-hand operand is
0, the JVM throws anArithmeticExceptionat runtime.
ArithmeticException. Instead, they return specific values defined by the Java Language Specification:
- NaN Operands: If either operand is
NaN, the result isNaN. - Infinite Dividend or Zero Divisor: If the dividend is
Infinityor-Infinity, or if the divisor is0.0or-0.0, or both, the result isNaN. This guarantees that operations likeInfinity % Infinityevaluate toNaN. - Finite Dividend and Infinite Divisor: If the dividend is finite and the divisor is
Infinityor-Infinity, the result is equal to the dividend. - Zero Dividend and Finite Divisor: If the dividend is
0.0or-0.0and the divisor is finite, the result is equal to the dividend.
Master Java with Deep Grasping Methodology!Learn More





