Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

diference between & and &&

 
Tal Tal
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
sven studde
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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() ).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic