Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## nooby question

I just wanted to know is it possible to do something like x==1|2 or do I have to do x==1 | x ==2?

Sorry for the waste of time. I haven't been able to find it on google (might not be searching the right terms).

2. ## Re: nooby question

Are you trying to make x an array?

3. ## Re: nooby question

wow, I didn't even explain it properly xD

I mean't in an if statement. if (x == 1|2) {}

Thanks again

4. ## Re: nooby question

Are you asking how to test if x is equal to 1/2?
What does the term: 1|2 mean?
The | operator is the bitwise OR. 1 ORed with 2 is 3. Try this:
System.out.println(3 == (1|2)); // this expression is true

5. ## Re: nooby question

| means or. So I want to know if it's possible to check if x == 1|2 (x is equal to 1 or 2) without having to use 2 statements if (x==1 | x==2) {}

6. ## Re: nooby question

Oh! ok. As far as i know, the correct if statement would be :

if ((x == 1)|(x==2)) {}

7. ## Re: nooby question

I'm guessing there's no way to make it shorter then?

8. ## Re: nooby question

Unfortunately, i don't think there is =(

9. ## Re: nooby question

Originally Posted by Bertorox
Oh! ok. As far as i know, the correct if statement would be :

if ((x == 1)|(x==2)) {}
'|' is a bitwise or operator - are you looking to do math, or to check equality? If the latter, use '||'. You could write this another way:
`if ( 1 <= x && <= 2 ){}`

Looking for shorthand ways of doing things could at times be considered bad practice, as it can obfuscate code and make it very unreadable - both by someone else and by yourself some time down the line when you try and figure out what the heck you were trying to do by looking at your own code.