-3

I need to implement switch statement for range values I can use if else but I think performance of switch will be better.

I have requirement like if value of variable is in range between 1-150 I will process my logic. If value of variable is in range between 150-300 then some other logic and if range is in 300-450 then some different logic and so on.

So how I can use switch in this case because generally I used switch with fixed values. Thanks in advance.

prank
  • 43
  • 11
  • 3
    Show us what you tried first. "_I can use if else but I think performance of switch will be better_" Stop worrying about "performance" on such simple examples. Worry about getting the program to run at all first. – Charles McKelvey Oct 10 '16 at 11:39
  • 3
    You could perform some arithmetic to convert each case to a particular constant. But you might be better off using `if` statements. `switch` statements are not for ranges. – khelwood Oct 10 '16 at 11:40
  • 8
    Should answer your question: http://stackoverflow.com/questions/10873590/in-java-using-switch-statement-with-a-range-of-value-in-each-case – tomas Oct 10 '16 at 11:40
  • 3
    Do you have evidence that using if/else does not meet your performance criteria? What *are* those performance criteria? – Jon Skeet Oct 10 '16 at 11:41
  • If you are concerned about performance, consider profiling your application. You'll probably find that the performance issues aren't in your `if` or `switch` statements, but in GUIs or string manipulation. – S.L. Barth is on codidact.com Oct 10 '16 at 11:47

2 Answers2

8

I suggest you use a formula

switch (value / 150) {
   case 0: // 0 - 149
          break;
   case 1: // 150 - 299
          break;
   case 2: // 300 - 449
          break;
   default: // otherwise.
}

If you use (value-1)/150 you get 1-150, 151-300, 301-450 etc

EDIT: case 0 will also accept -148 - 0 in switch ((value-1)/150){...} due to the nature of integer division. To avoid this if/else statements, as well as the conditional operator, can be used.

Brad Yuan
  • 13
  • 2
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

It's not possible.

If you check the Java Language Specification for switch, you'll see that the expression after case must be a ConstantExpression or an EnumConstantName.
Neither of these can be a range.

A few alternatives have been pointed out in the comments. You could use an if statement; it shouldn't make a lot of difference performance-wise, unless you have a really large amount of cases.
Or you could (as per this answer, linked in the comments by @tomas) create separate function to distinguish between the different ranges.

If the ranges are regular (e.g. 101-200, 201-300, etc) you could also use a formula. Beware of rounding errors! Test the edge cases of your formula to make sure it is correct.

Community
  • 1
  • 1