Is Java's operator% ever overflowing?

In C and C ++, the behavior INT_MIN % -1

seems to be undefined / platform dependent as per Shafik's post .

Does the% operator overflow occur in Java?

Consider this piece of code:

public class Test {
    public static void main(String[] args) {
        // setup variables:
        byte b = Byte.MIN_VALUE % (-1);
        short s = Short.MIN_VALUE % (-1);
        int i = Integer.MIN_VALUE % (-1);
        long l = Long.MIN_VALUE % (-1);

        // my machine prints "0" for all:
        System.out.println(b);
        System.out.println(s);
        System.out.println(i);
        System.out.println(l);
    }
}

      

Is there a platform independent assurance that the above results 0

?

+3


source to share


1 answer


Have a look at JLS 15.17.3 which says:



In C and C ++, the remainder operator only accepts integer operands, but in the Java programming language, it also accepts floating point operands.

The remainder operation for operands that are integers after the binary code numerical promotion (§5.6.2) yields a result value such that (a / b) * b + (a% b) equals a. This identity holds true even in the special case where the dividend is a negative integer with the largest possible value for its type and the divisor is -1 (remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative and can only be positive if the dividend is positive.

+6


source







All Articles