-2

Today I came across a very different coding style of declaring int in Java, being curious I tried in IntelliJ and it's working but there is no explanation on Google how it's working.

 int i = 1 | 2 | 3 | 4 | 5;
 System.out.println("i = " + i);

The output is 7. Any explanation?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
shrikant.sharma
  • 1
  • 11
  • 31

1 Answers1

0

That's bit-wise OR.

When you OR the bits of the binary representations of all these integers, you get 7:

1 == 0..00001
2 == 0..00010
3 == 0..00011
4 == 0..00100
5 == 0..00101
-------------
7 == 0..00111
Eran
  • 374,785
  • 51
  • 663
  • 734
  • Thanks @Eran, I know bitwise OR operator and have used it in assigning objects also. but never thought it can be used in the declaration of primitive as well. – shrikant.sharma Sep 02 '19 at 07:00