This week's giveaway is in the Spring forum.We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!

# Assigment operation in Rectangle2D class

Henrique Boreg
Greenhorn
Posts: 23
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 ??

ps. OUT_LEFT = 1, OUT_TOP = 2, OUT_RIGHT = 4, OUT_BOTTOM = 8

Thanks.

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24208
35
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".

Henrique Boreg
Greenhorn
Posts: 23