Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Remainder operator (%)

The % operator computes the remainder of integer or floating-point division. Its result is not necessarily nonnegative.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

dividend % divisor

In dividend % divisor, the left operand is the dividend and the right operand is the divisor. Operands undergo binary numeric promotion.

For integers, the quotient is truncated toward zero. A nonzero remainder has the dividend's sign, not the divisor's: -17 % 5 gives -2. Thus % does not always mean nonnegative modulo.

If both operands are of an integral type after promotion, a zero divisor causes ArithmeticException. If the promoted operands are both float or both double, a zero divisor produces NaN without throwing that exception. For example, 5.5 % 0 produces NaN because the integer 0 is promoted to double.

To test integer divisibility, use n % d == 0 when d != 0.

Examples

public class Main {
    public static void main(String[] args) {
        System.out.println(17 % 5);
        System.out.println(-17 % 5);
        System.out.println(17 % -5);
        System.out.println(5.5 % 2.0);
        System.out.println(5.5 % 0.0);
    }
}

Result

2
-2
2
1.5
NaN

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources