This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello, I was looking over the Rectangle2D class in java.awt.geom, and I came across a method that given an (x,y) point, returns its relative position to the rectangle (eg. left, right, bottom or top). Pretty much, the whole method is:
my question is, what exactly is going on in the assignments such as out |= OUT_TOP | OUT_BOTTOM ??
1, 2, 4, and 8 are all integers with a single bit set -- binary 0001, 0010, 0100, and 1000, respectively. The "|" operator is the bitwise "or" operation, which returns a value that has 1-bits in every location that is a 1 in either of its operands. Because those constants each have a single "1" bit in them, you can use a single int to represent a set of them -- i.e., OUT_TOP | OUT_LEFT means 1010, and you can recover each of the constituent parts separately. Given a point that's above and to the left of the rectangle, this routine will return OUT_TOP | OUT_LEFT or binary 0011, or 3 decimal. You can then say
"&" is bitwise "and", and its result has a 1 bit only in those locations where both arguments have a "1".