aspose file tools
The moose likes Beginning Java and the fly likes How does the % operator work? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How does the % operator work?" Watch "How does the % operator work?" New topic
Author

How does the % operator work?

Ethan Bauer
Greenhorn

Joined: Sep 22, 2010
Posts: 18


Could anyone explain how you use % as a logical operator?
Maybe another example is better but this was the one I found in the course I'm taking on Java..
Wouter Hermans
Greenhorn

Joined: Oct 16, 2010
Posts: 13
% gets you the remainder of a division. In this case, a number is odd when the remainder is not zero when you divide it by two.
Kr Manish
Ranch Hand

Joined: Jul 30, 2010
Posts: 138
number % 2 == 0 translates to : is the number an even number ? (hope you realize, if after dividing a number remainder is zero, it is even number)
but the *full* code snippet looks strange to me. Value of odd will be false when number is even, and vice versa. wonder what the code does, though.


You know what I am saying ?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32694
    
    4
There is a neater way to do itBecause the % operator has a higher precedence than !=, you don't need any (round brackets).

There is a quicker way to do itNote that the & operator will give much faster performance than % because it is simply comparing bits, not dividing, but the (round brackets) are needed here. I shall leave the reader to work out how it works, and also to work out which range of operands it will work for.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32694
    
    4
And welcome to the Ranch , Wouter Hermans.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: How does the % operator work?
 
Similar Threads
~ operator
Easy el question
division and testing for whole number result
once again instanceof
How to create this simple program in Java?