File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "and" Watch "and" New topic


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)


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.

Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 17423

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

An IDE is no substitute for an Intelligent Developer.
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().


Java API Documentation
The Java Tutorial
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
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
I agree. Here's the link:
subject: and
jQuery in Action, 3rd edition