I do the following code
int cnt=1;
switch(cnt){
case (cnt<=10): System.out.println("Less than 10");
break;
case (cnt<=20): System.out.println("Less than 20");
break;
case (cnt<=30): System.out.println("Less than 30");
break;
}
There are some questions available about this problem. But i didn't got proper answer or the answer is not fulfill my needs. I got the answers to this problem is use multiple if else statements. But I want to know why operators not work in java switch case?
That's simply not how switch/case statements work - in Java or in various similar languages (C, C++, C#). It's not the point of them.
Switch/case statements aren't a sequence of conditions - they're a sequence of constant values (with associated code), along with a single expression which is evaluated, and then the code associated with the result of that expression is executed.
If you want a sequence of conditions, just use if/else. There isn't any other way, in Java. There are languages which have condition matching like this, but Java isn't one of them. (Note that in such languages, you need careful rules for what can happen if multiple conditions are matched - as they could be in your example, if cnt
is 0 for example...)
See more on this question at Stackoverflow