1

Could somebody explain me why System.out.println((12 & 9)); prints 8, please?

I do not understand the logic of the & operator at this context.

Thanks!

2

4 Answers 4

18

It's binary.

12 is 1100 and 9 is 1001.

Applying the logical "and" & operator gives 1000, which is 8.

8
It is Binary representation. (Machine Understandable language)
Here first place resembles  value - 1 (Right to Left)
Second place resembles  value - 2 (Right to Left)
Third place resembles  value - 4 (Right to Left)
Fourth place resembles  value - 8 (Right to Left)

& says 1 and 1 is true(i.e., 1), rest of combinations are false (i.e., 0)

     12 - 1100
      9 - 1001
===============
      8 - 1000
4

& is a bitwise and operator.

12 = 1100
9 = 1001
1100 & 1001 = 1000
1000 = 8
1

The logic for printing 8 is the same as System.out.println((12 + 9)); prints 21.

The operators get preference over the called method, so and operation is performed first then anything else is let to happen.

Here you are doing simple logical and which should result in 8, as following:

12 is 1100 and 9 is 1001.

& operation will result in 1000. where 1000 is 8.

Not the answer you're looking for? Browse other questions tagged or ask your own question.