We explore the remainder operator - %
- in Java. This is frequently called
modulo, or "mod" for short. However, modulo usually only returns positive
numbers, whereas the remainder (%
) might return negative numbers. In the
Java
Language Specification we do not find modulo mentioned anywhere, only
remainder.
It's a subtlety, and you will find lots of Java texts and articles calling
%
"mod" or "modulo", when the correct term is remainder.
If you ever asked about this in a job interview, I'd recommend not acting too clever, because no one likes a smart-ass. Also, the interviewer might not know the difference, and thus you might disqualify yourself for the job, because they think you are ignorant :-)
Lastly, it is interesting to note that division and remainder calculations are
among the most expensive on CPUs. We would generally avoid
%
because of this.
We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...