1. ## [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...

2. 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,

Java Code:
`1 % intVariable2`
evaluates first. That is 1. And then it's added to 9, result is 10. Hope it's clear to you.

3. 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 +
Last edited by Norm; 10-12-2008 at 02:59 PM.

4. Member
Join Date
Oct 2008
Location
UK
Posts
65
Rep Power
0
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

5. 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. :)

6. Member
Join Date
Oct 2008
Location
UK
Posts
65
Rep Power
0
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

7. ## According to Sun...

According to Sun's JSL the rules for the Remainder Operator (%) are:

Expressions

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

Thanks!

9. Thanks everybody!
I can move on to chapter 2 now. :)

10. 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•