aspose file tools*
The moose likes Beginning Java and the fly likes What's the difference between & and &&? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What Watch "What New topic
Author

What's the difference between & and &&?

André Asantos
Ranch Hand

Joined: Nov 23, 2009
Posts: 234
What's the difference between & and &&?

fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

&& (and | vs || is the same) is the shortcut operator. As soon as you can determine the results, it stops. This is useful for things like

if (myObject != null && myObject.doIt())

if the object is null, we know the expression is false, so we don't bother calling myObject.doIt(), which is a good thing, since that would throw a null pointer exception.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
André Asantos
Ranch Hand

Joined: Nov 23, 2009
Posts: 234
thanks a lot for helping....

if any guy also needs that if speaks Portuguese check it out the link http://www.guj.com.br/posts/list/58646.java I found out too in detail...
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

For more details, see JLS - 15.23 Conditional-And Operator &&.


"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
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39773
    
  28
Another thing is that && and || have lower precedences than & ^ (exclusive-or) and |. The single-stroke operators & ^ and | are overloaded; they are applied to integer numbers and secondarily also applied to Boolean values. Boolean values include un-boxed java.lang.Boolean objects and boolean primitives.

Note the Java™ Tutorials refer to && as conditional and on one page, which is correct, and logical and, which may be incorrect, on another page.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Campbell Ritchie wrote:... Note the Java™ Tutorials refer to && as conditional and on one page, which is correct, and logical and, which may be incorrect, on another page.

You're right. The JLS defines a single '&' as "bitwise" or "logical" (JLS - 15.22). The double '&&' is "conditional" (JLS - 15.23).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What's the difference between & and &&?