Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

and

 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 &&?
 
Edwin Keeton
Ranch Hand
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 18009
47
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if ( (1 > 2) && deleteAllMyFiles() ) {
System.out.println("This can never happen");
}
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roger
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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) ) ...

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic