aspose file tools*
The moose likes Beginning Java and the fly likes and Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "and" Watch "and" New topic
Author

and

Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
So, by playing the Rules Roundup, it has come to my attention that I can just as correctly write

if( x<5 & y>3)

as

if( x<5 && y>3)

so why have I, up until this point, always written &&, and always seen it written as &&?


I've heard it takes forever to grow a woman from the ground
Edwin Keeton
Ranch Hand

Joined: Jul 10, 2002
Posts: 214

is a "short-circuit" boolean operation. So if the first (left-to-right) expression evaluates false, the second expression is not evaluated since false and true evaluates false.

evaluates both expressions regardless. This is significant if your code depends on the second expression being evaluated or not.


SCJP, SCWCD
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16145
    
  21

if ( (1 > 2) && deleteAllMyFiles() ) {
System.out.println("This can never happen");
}


Customer surveys are for companies who didn't pay proper attention to begin with.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Tim Holloway:
if ( (1 > 2) && deleteAllMyFiles() ) {
System.out.println("This can never happen");
}


As Edwin explains above, this snippet will not only skip the println() call, but it will also skip deleteAllMyFiles().

Layne


Java API Documentation
The Java Tutorial
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
Roger
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I recently found this in code:

if( a != null & a.equals("b") ) ...

which still gets a null pointer exception when a is null. They intended a shortcut && in there to make that work. Being a PITA I changed it to:

if ( "b".equals(a) ) ...



A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
wood burning stoves
 
subject: and