[java] OR operator in switch-case?

Let's take a simple switch-case that looks like:

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.someValue :
        case R.id.someOtherValue:
            // do stuff
            break;
    }
}

I wonder why it is not allowed to use the || operator? Like

switch (v.getId()) {
    case R.id.someValue || R.id.someOtherValue:
        // do stuff
        break;
}

The switch-case construct is pretty similar to an if-else statement, you can use the OR operator in an if however. What are the backgrounds for a switch-case to not accept this operator?

This question is related to java switch-statement

The answer is


You cannot use || operators in between 2 case. But you can use multiple case values without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a "break". As a result these cases will share the same code.

switch(value) 
{ 
    case 0: 
    case 1: 
        // do stuff for if case 0 || case 1 
        break; 
    // other cases 
    default: 
        break; 
}

Switch is not same as if-else-if.

Switch is used when there is one expression that gets evaluated to a value and that value can be one of predefined set of values. If you need to perform multiple boolean / comparions operations run-time then if-else-if needs to be used.


dude do like this

    case R.id.someValue :
    case R.id.someOtherValue :
       //do stuff

This is same as using OR operator between two values Because of this case operator isn't there in switch case


foreach (array('one', 'two', 'three') as $v) {
    switch ($v) {
        case (function ($v) {
            if ($v == 'two') return $v;
            return 'one';
        })($v):
            echo "$v min \n";
            break;


    }
}

this works fine for languages supporting enclosures