Reputation:
I do program with Java for about one year, but still found something I do not know. How does:
new Font(FontFamily.TIMES_ROMAN, 12, 1 | 4);
How | does work with integers?
Thank You
P.S. I googled a lot.
Upvotes: 5
Views: 482
Reputation: 49412
It is a bitwise OR
operator , operates on one or more bit patterns or binary numerals at the level of their individual bits.
The bitwise ^ operator performs a bitwise exclusive OR operation.
OR bitwise operation will return 1 if any of operand is 1 and zero only if both operands are zeros.
You can get the complete description in the JLS 15.22.1.
0|0 = 0
0|1 = 1
1|0 = 1
1|1 = 1
Hence in your case , the operands are 1
and 4
. Converting them into binary (only the last 4 digits) will be 0100
and 0001
respectively. Apply the |
now bit by bit :
0 1 0 0
0 0 0 1
---------
0 1 0 1 = (5 in base 10)
Upvotes: 7
Reputation: 111349
The |
operator calculates the "bit-wise OR" of its operands. To understand it you have to convert the operands to binary: it produces a "0" bit if the bit is not set in either numbers, and a "1" bit if it is set in either.
With your numbers, the result of 4|1
is 5 because:
4 = 100
1 = 001
4|1 = 101 = 5
The bit-wise OR operator is related to the "bit-wise AND" operator &
, which produces a "0" if the bit is not set in one of the numbers and a "1" bit if it is set in both.
Since these operators work on the bit-wise representation of their arguments they can be hard to understand when you're used to working on decimal (base 10) numbers. The following relation holds, which makes it easy to derive the result of one when you have the other:
a + b = (a|b) + (a&b)
Upvotes: 11
Reputation: 1170
The |
is called bitwise OR. This works by:
||
) on each digit in a matching position (0 is false, 1 is true)For example,
100 | 4
OR 001 | 1
-------+--
101 | 5
The properties on the Font
constructor are designed so in binary, exactly one digit is a 1. By ORing these numbers, you get the digits turned on that represent the options that are ORed.
Upvotes: 1