Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Assigment operation in Rectangle2D class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Assigment operation in Rectangle2D class" Watch "Assigment operation in Rectangle2D class" New topic

Assigment operation in Rectangle2D class

Henrique Boreg

Joined: Aug 11, 2005
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


"I wrote an all-Java OS in 1998 but can't be sure if or how it works... it's still booting"
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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

[Jess in Action][AskingGoodQuestions]
Henrique Boreg

Joined: Aug 11, 2005
Posts: 23
thanks for the reply Ernest, it was really helpful.
I agree. Here's the link:
subject: Assigment operation in Rectangle2D class
It's not a secret anymore!