0

Is it possible to use 'or' operator multiple times without getting an error in java

 if(var=="20"|"22"|"24"....)) 

3 Answers 3

4

| is bitwise OR operator. You need to use ||

Syntax should be something like below for your requirement

if(var.equals("20")|| var.equals("22")|| var.equals("24")) 
Sign up to request clarification or add additional context in comments.

9 Comments

I want to use variable only one time. Is it possible like that?
No, it is not possible with API calls.
@Bohemian OP wants logical OR. For instance, if OP wasn't using strings but rather numbers, 20|22|24 would be disastrous.
@2rs2ts the opening sentence is wrong. | is both bitwuse or and the non-short circuiting logical OR operator
|| is NOT required here! I could code it with | and it would work
|
1

Lots of problems here.

First, you can't compare strings using ==, which tests if the 2 operands are the same object. Use equals():

if (var.equals("21")) 

Next, you can't group up operands like that, you must use separate calls to equals(), but instead of that you can also do this:

if (Arrays.asList("20", "22", "24", ....).contains(var)) 

3 Comments

This is less efficient than the switch statement. That can use the hashCode to (usually) not-compare many Strings. I agree that this is easier to maintain, so probably a better choice (but moving the Arrays.asList out of the loop would be preferred if this is in a loop).
@gabor ... 97% of the time, premature optimization is the root of all evil - Donald Knuth
I agree and aware of this. I was just pointing out that similar things were the reason of introducing the switch with Strings statement.
0

I guess you are looking for the switch statement (works with strings too, since Java 7). Using or is not what you want in my opinion. Example:

switch (var) { case "20"://document fall-through to prevent future changes case "22"://no break here either case "24": //do what you want. break; } 

Comments