Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By Norm

Thread: What does the ampersand do?

  1. #1
    Derpy is offline Member
    Join Date
    Jul 2012
    Rep Power

    Default What does the ampersand do?

    Right, I recently came across with this short piece of code:

    Java Code:
        for(int a=0; a<3; a++)
             if( (a&1)==1)
    Outputs: "bar, foo, bar, foo"

    The thing I do not understand in this code is the line " if( (a&1)==1 )". Doesn't & stand for "AND" in Java? IF a == 1 AND 1 == 1 DO... But that in that case the code would simply output "bar, foo, bar, bar". Could someone please explain this line to me?

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Eastern Florida
    Rep Power

    Default Re: What does the ampersand do?

    The & is the bitwise AND operator. See:
    Bitwise and Bit Shift Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

    The expression: (a&1)==1 tests if the low order bit of the variable a is 1. That would be true if a is an odd number.
    Derpy likes this.
    If you don't understand my response, don't ignore it, ask a question.

Posting Permissions

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