This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Hello, 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. Thomas
Dave Landers
Ranch Hand
Joined: Jul 24, 2002
Posts: 401
posted
0
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
Sheriff
Joined: Dec 10, 2001
Posts: 7023
posted
0
The || and && operators are sometimes called "short-circuiting" operators.