2

I tried compiling and running the following code

public static void main(String... args) {
    int x = 1 | 2 | 3 | 4;
    //int x = 1 | 1 | 1 ;
    //int x = 1 | 2 ;
    //int x = 2 | 1 ;
    System.out.println(x);
}

I tried in dot net and its not working how come its working in java ?? How is this code being evaluated to produce an answer ??

Girish Nair
  • 5,148
  • 5
  • 40
  • 61

3 Answers3

7
1 | 2 = 00000001 | 00000010 = 00000011 = 3
3 | 3 = 00000011 | 00000011 = 00000011 = 3
3 | 4 = 00000011 | 00000100 = 00000111 = 7
gluckonavt
  • 236
  • 1
  • 4
5

That is called bitwise operator in Java. It operates on the bits of the operands.The bitwise | operator performs a bitwise inclusive OR operation.

If you observer the lower order bits :

1 - 0001
2 - 0010
3 - 0011
4 - 0100

Biwise OR of each of them will produce 0111 which is 7.You can refer to the JLS 15.22.1 for more.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

This is example of bitwise inclusive OR or operator. And the result will be 7.

1 - 0001
2 - 0010
3 - 0011
4 - 0100
---------
7 - 0111

I do not know how did you used it in "dot net", but it should work. This reading prove it