This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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 &&?



André AS
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10908
    
  12

&& (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: 36453
    
  15
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 &&?
 
Similar Threads
ClassLoader
Lightweight and heavyweight containers
SCJA?
Google Select
what's the difference between / and // in Xpath