It's not a secret anymore!
The moose likes Beginning Java and the fly likes logical operators for AND and OR Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "logical operators for AND and OR" Watch "logical operators for AND and OR" New topic

logical operators for AND and OR

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
I tried out a lot of comparisons with | and || and both
Had the same results.
So what is the difference beween | and || for the OR-Operator
And & and && for the AND-Operator.
I think | and || are the same and they are true if one expression is true.
When you put an AND by & or && both expressions have to be true.
So what is the difference between & and && => AND-Operation
Between | and || => OR-Operation???
int a = 3;
int b = 4;
if (a == 2 | b > 0 )
if (a ==2 || b >
if (a ==3 && b==2)
if (a == 3 & b==2)

Appreciate Your Answers.
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
The || and && operators are "short cutting" operators. That is, as soon as the JVM can tell what the answer's going to be it stops. The | and & operators always evaluate everything.
The advantage is that you can do things like this:
if ( foo == null || foo.length() == 0 ) // etc
If foo is null, then the first part is true and no matter how the second part comes out the answer is always true. So the VM never will run "foo.length()" if foo is null.
If foo is non-null, it will go on to the length() test and see how that comes out.
So in the above case, you just can't get a NullPointerException.
But if you changed that to
if ( foo == null | foo.length() == 0 ) // etc
then you would get a NullPointerException if foo were null.
There are all kinds of uses for both kinds of operators, once you know how they work.
One other difference: Both kinds will do "boolean" tests, but only the | and & operators will do "bitwise" tests (and/or every bit in some number).
So 4 & 3 = 0 (in binary 0100 & 0011 = 0000)
4 | 3 = 7 (0100 | 0011 = 0111).
You can't do those sorts of things with && and ||.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
The || and && operators are sometimes called "short-circuiting" operators.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: logical operators for AND and OR
It's not a secret anymore!