Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic value for CASE in java SWITCH

I need to implement switch case statement with dynamic value for case as below.

int v1 = 5;
int key = xx.getKey();

switch (v1) {
   case key:
       .......
   case key+1:
       .......
   case key+2:
       .......
   default:
       .......
}

When using this, java complains "case expressions must be constant expressions". Is there a way to use dynamic values in case. (switch variable is also dynamic value)

like image 552
Dhanushka Kumara Avatar asked Feb 07 '26 06:02

Dhanushka Kumara


1 Answers

You cannot have non-constant expressions as cases in your switch statement. However, you can make the cases constant by subtracting key from v1:

switch (v1 - key) {
   case 0:
       .......
   case 1:
       .......
   case 2:
       .......
   default:
       .......
}

However, this only works because you have simple cases. As @BorisTheSpider points out, in the more general case, you'd need to use if...else statements.

like image 129
Andy Turner Avatar answered Feb 08 '26 20:02

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!