2

I cannot understand to why this syntax does not generate any kind of compile time or run time errors ?

int i=2;

switch(i ^ 3){       ---- > this part
 case 8: System.out.print("Eight"); break;
 default: System.out.print("Default");
}

It prints Default, so what does this ( i ^ 3 ) do in the switch condition ?

san A
  • 177
  • 2
  • 13

3 Answers3

1

i ^ 3 is i XOR 3 (2 XOR 3), which is 1 (10 XOR 11 is 1). It's not a power operator, so it doesn't return 8. Therefore the default section of the switch statement is reached.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

i is equal to 2.

2^3 = 1. (XOR operation).

10 //2
11 // 3 (XOR)
--
01 //1

So, it sets the value of 1 for the switch condition.

dryairship
  • 6,022
  • 4
  • 28
  • 54
0

^ is Bitwise XOR where i ^ 3 generate integer result.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307