# [SOLVED] Modulus/Remainder results

• 10-12-2008, 10:46 AM
antgaudi
[SOLVED] Modulus/Remainder results
What would be the result of longVariable?

int intVariable1 = 9;
int intVariable2 = 10;
longVariable = intVariable1 + 1 % intVariable2;

I would guess it would be 0 since 10 goes into 10 once and nothing remains...the correct answer is 10 and I have NO idea why...

• 10-12-2008, 11:03 AM
Eranga
No it's 10, I mean the result is 10 not 0 as you expect.

It's all about operators presidencies in Java. The % operator has higher precedence than + operator. So in your code,

Code:

`1 % intVariable2`
evaluates first. That is 1. And then it's added to 9, result is 10. Hope it's clear to you.
• 10-12-2008, 02:35 PM
Norm
Quote:

What would be the result
If you have a compiler and a jvm, the fastest and most accruate method to find the answer is to use them.

intVariable1 + 1 % intVariable2
is the same as
intVariable1 + (1 % intVariable2)

% has higher precedence than +
• 10-12-2008, 02:53 PM
Paul Richards
well

1%n is always 1 for n>1

reason is... if you divide 1 by a number (unless that number is also 1) you get an answer of zero, and a remainder of 1.

So your sum is just 1+9=10
• 10-12-2008, 05:03 PM
antgaudi
how is the remainder 1 if the answer is 0?
nothing remains...?

why do u not get 1 when it's 1%1?

I'm so confused...and I heard this is 3rd grade stuff... :-P

thanks for the feedback. :)
• 10-12-2008, 07:59 PM
Paul Richards
Quote:

Originally Posted by antgaudi
how is the remainder 1 if the answer is 0?
nothing remains...?

why do u not get 1 when it's 1%1?

I'm so confused...and I heard this is 3rd grade stuff... :-P

thanks for the feedback. :)

You need to understand modular arithmetic, I would just google it. The % symbol is referred to as mod a lot of the time.

Let me give you some examples:

24%4 is 0 since
4x6+0 = 24

23%4 is 3 since
4x5+3 = 23

1%4 is 1 since
4x0+1 = 1

Hope that helps you more than it hinders
• 10-12-2008, 08:24 PM
CJSLMAN
According to Sun...
According to Sun's JSL the rules for the Remainder Operator (%) are:

Expressions
• 10-12-2008, 11:22 PM
antgaudi
Oh my goodness, Paul, you have really shed some great light on this!
You put it in such a colorful, visual, way!

Thanks!
• 10-12-2008, 11:28 PM
antgaudi
Thanks everybody!
I can move on to chapter 2 now. :)
• 10-13-2008, 03:49 AM
Eranga
Quote:

Originally Posted by antgaudi
Oh my goodness, Paul, you have really shed some great light on this!
You put it in such a colorful, visual, way!

Thanks!

Module operator is not specific to Java. Used in many programming languages.

And also, if you have solve this question please mark it as solved.