-4

I'm new at java, and I'm a little confused by the functions '|' in non void java functions return

private int donUnderstand() {
    return 1 | 2 | 3 | 4; //return 7, where is 7 come from?
}

Function above will return 7, but I don't get it where is 7 come from. I need some explanation. What is '|' character really mean at that function?

2 Answers2

6

| is the bitwise OR operator in Java. In your example, it ORs together 1, 2, 3 and 4. Their binary representation is 0001, 0010, 0011 and 0100, respectively. This results in 0111, which is the binary representation of 7.

1 == 0001
2 == 0010
3 == 0011
4 == 0100
----------- OR
7 == 0111
pappbence96
  • 1,164
  • 2
  • 12
  • 20
0

| is the bitwise OR operator. That is it would do an OR operation on each bit of the numbers and return the result. For example:

a = 5 = 0101 (In Binary)

b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7

 0101

| 0111
 ________
  0111  = 7 (In decimal) 

More info here: Bitwise OR

p.mathew13
  • 920
  • 8
  • 16