This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes diference between & and && Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "diference between & and &&" Watch "diference between & and &&" New topic

diference between & and &&

Tal Tal
Ranch Hand

Joined: Dec 10, 2003
Posts: 40
what is the diference between & and && operators?
are they both represent the "and" operator, or is there a differnce between them?

marc weber

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
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

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() ).
I agree. Here's the link:
subject: diference between & and &&
It's not a secret anymore!