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
  • 179
  • 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
  • 374,785
  • 51
  • 663
  • 734
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
  • 5,842
  • 2
  • 29
  • 53
0

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

Suresh Atta
  • 118,038
  • 37
  • 189
  • 297