Wrong and Wrong Again
Java's Ternary Operator - No, it's Not!
I need to stop referring to the ternary operator (? :
) in Java as “the ternary operator”. It is not the ternary operator; it is a ternary operator. It may currently be the only ternary operator in the core Java Language Specification - but even so, I should call it by its correct name, which is the conditional operator.
Java's Modulo Operator - No, it's Not!
I need to stop referring to the modulo (%
) operator in Java as “the modulo operator”. It’s the remainder operator.
Java does not have a modulo operator.
Here is how Java’s remainder operator behaves, along with division (assuming int
):
Expression | Result |
---|---|
5/3 | 1 |
5%3 | 2 |
5/(-3) | -1 |
5%(-3) | 2 |
(-5)/3 | -1 |
(-5)%3 | -2 |
(-5)/(-3) | 1 |
(-5)%(-3) | -2 |
Perhaps even more importantly, I need to understand that modulo operators in other languages may not always work in a consistent way when it comes to how negative numbers are handled. Here is a great article about that:
https://torstencurdt.com/tech/posts/modulo-of-negative-numbers/
A table of results from the above article:
Language | 13 mod 3 | -13 mod 3 | 13 mod -3 | -13 mod -3 |
---|---|---|---|---|
C | 1 | -1 | 1 | -1 |
Go | 1 | -1 | 1 | -1 |
PHP | 1 | -1 | 1 | -1 |
Rust | 1 | -1 | 1 | -1 |
Scala | 1 | -1 | 1 | -1 |
Java | 1 | -1 | 1 | -1 |
Javascript | 1 | -1 | 1 | -1 |
Ruby | 1 | 2 | -2 | -1 |
Python | 1 | 2 | -2 | -1 |
Author northCoder
LastMod 21-May-2021