Modulo Operation in Java

Modulo Operation in Java

In Java, Math.floorDiv and Math.floorMod behave better than % and / , respectively, because the latter interpret the operations on negative numbers incorrectly.

Here is a small case:

1
2
3
4
5
6
7
8
9
public class ModDemo {
public static void main(String[] args) {
System.out.println(-18 % 10);
System.out.println(Math.floorMod(-18, 10));

System.out.println(-18 / 10);
System.out.println(Math.floorDiv(-18, 10));
}
}

The output of the above code is:

mod_demo

While in Python, we do not have this issue:

mod_demo_2