i cant understanding negative 2 and positive 2 x=-10 % 4; System.out.println(“-10% 4 : “+x); //-2 [closed]

The operator % divides the left side by the right side as / would do, but the result is the remainder of the division and not the result of the division itself.

See this example where your code was extended and slightly changed:

public static void main(String[] args) {
    int x;
    int y;

    x = -10 % 4; // calculates the remainder of...
    y = -10 / 4; // ... this calculation
    System.out.println("-10 /  4 = " + y + ", remainder: " + x);

    x = -10 % -4;
    y = -10 /- 4;
    System.out.println("-10 / -4 = " + y + ", remainder: " + x);

    x = 10 % -4;
    y = 10 / -4;
    System.out.println(" 10 / -4 = " + y + ", remainder: " + x);

    x = 10 % 4;
    y = 10 / 4;
    System.out.println(" 10 /  4 = " + y + ", remainder: " + x);
}

This outputs

-10 /  4 = -2, remainder: -2
-10 / -4 = 2, remainder: -2
 10 / -4 = -2, remainder: 2
 10 /  4 = 2, remainder: 2

Leave a Comment