The % remainder operator in Java

hello world
Aug 28, 2017 · 1 min read

what is the result of 3 % 4?

what is the result of -3 % 4?

what is the result of -3 % -4?

The answer is it’s language dependent!

I will tell you about the magic formula that Java uses to calculate the reminder of two quantities (yes, I call them quantities since you can use it for both integer and floating point numbers).

Here you go the formula:

a = (a/b)*b + a%b

so a%b = a- (a/b)*b

note: the “/” is the integer division

take some time to try a few examples yourself with this formula :)

-3 % 4 = -0*(4) + -3 => -3%4 = -3

3 % -4 = -0*(-4) + 3 => 3%4 = 3

3.2 % -4 = -0*(-4) + 3.2 => 3%4 = 3.2

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade