| Author |
diference between & and &&
|
Tal Tal
Ranch Hand
Joined: Dec 10, 2003
Posts: 40
|
|
hello what is the diference between & and && operators? are they both represent the "and" operator, or is there a differnce between them? Thanks
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Applied to integral primitive operands, & is a "bitwise and" operator. Applied to boolean operands, & is a "logical and" operator. The && operator is a short-circuiting "logical and" operator that can be applied only to booleans. If the left operand evaluates to false, then the expression's result is already known (because the result is false regardless of the right operand's value), and so the operation "short circuits" and does not evaluate the right operand. In other words, the right operand evaluates only if the left operand evaluates to true.
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
sven studde
Ranch Hand
Joined: Sep 26, 2006
Posts: 148
|
|
Just use && all the time right? It's more efficient since it doesn't evaluate the right side if the left side is false. Well, try running the following code, and then run it again and change & to && to see the difference: Sometimes you might want the right side to evaluate regardless of what the left side evaluates to. [ October 27, 2006: Message edited by: sven studde ]
|
 |
Jing Liang
Ranch Hand
Joined: Oct 23, 2006
Posts: 40
|
|
A & B Both A and B will be evaluated. It doesn't matter if A and B are true or false A && B If A is false, B will not be evaluated. So if A is true then B will be evaluated.
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
In addition to efficiency, the short-circuiting feature is commonly used to safeguard against NullPointerExceptions. For example, if( myRef.getBoolean() ) could throw a runtime exception if myRef turns out to be null. This can be prevented by short-circuiting, if( myRef != null && myRef.getBoolean() ).
|
 |
 |
|
|
subject: diference between & and &&
|
|
|