Search code examples
javanegative-numbermodulo

Java MOD operator returns negative value


I have this method:

private static int generateNo(int randomNo, int value){
    return   ((randomNo*value)%256);
}

in my example randomNo = 17719 qValue = 197920

When I calculate it with calculator the returned value should be 224, however, when I run the program it returns -32.

can anyone explain it please.


Solution

  • A little hint. If you have unexpected negative value when multiply (or sum) numbers, mostly this is number overflow:

    private static int generateNo(int randomNo, int value) {
        return (int)(((long)randomNo * value) % 256);
    }