java - OR operator in switch-case? -


let's take simple switch-case looks like:

@override public void onclick(view v) {     switch (v.getid()) {         case r.id.somevalue :         case r.id.someothervalue:             // stuff             break;     } } 

i wonder why not allowed use || operator? like

switch (v.getid()) {     case r.id.somevalue || r.id.someothervalue:         // stuff         break; } 

the switch-case construct pretty similar if-else statement, can use or operator in if however. backgrounds switch-case not accept operator?

what backgrounds switch-case not accept operator?

because case requires constant expression value. , since || expression not compile time constant, not allowed.

from jls section 14.11:

switch label should have following syntax:

switchlabel:
case constantexpression :
case enumconstantname :
default :


under hood:

the reason behind allowing constant expression cases can understood jvm spec section 3.10 - compiling switches:

compilation of switch statements uses tableswitch , lookupswitch instructions. tableswitch instruction used when cases of switch can efficiently represented indices table of target offsets. default target of switch used if value of expression of switch falls outside range of valid indices.

so, cases label used tableswitch index table of target offsets, value of case should known @ compile time. possible if case value constant expression. , || expression evaluated @ runtime, , value available @ time.

from same jvm section, following switch-case:

switch (i) {     case 0:  return  0;     case 1:  return  1;     case 2:  return  2;     default: return -1; } 

is compiled to:

0   iload_1             // push local variable 1 (argument i) 1   tableswitch 0 2: // valid indices 0 through 2  (notice instruction?)       0: 28             // if 0, continue @ 28       1: 30             // if 1, continue @ 30       2: 32             // if 2, continue @ 32       default:34        // otherwise, continue @ 34 28  iconst_0            // 0; push int constant 0... 29  ireturn             // ...and return 30  iconst_1            // 1; push int constant 1... 31  ireturn             // ...and return 32  iconst_2            // 2; push int constant 2... 33  ireturn             // ...and return 34  iconst_m1           // otherwise push int constant -1... 35  ireturn             // ...and return 

so, if case value not constant expressions, compiler won't able index table of instruction pointers, using tableswitch instruction.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -