wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes writing If blocks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "writing If blocks" Watch "writing If blocks" New topic
Author

writing If blocks

rachana ravali
Ranch Hand

Joined: Jun 20, 2006
Posts: 32
Hi ,
Is there any difference in terms of performance or other , if we write too many conditions in one if block.i.e like ...
if (condition1 && condition2 && condition3 &&.....sofar)
or is there any good if we split the conditions like this...
if(condition1)
{
if(condition2)
{ ......

Please let me know.
Giovanni De Stefano
Ranch Hand

Joined: Aug 17, 2004
Posts: 144
Hello Rachana,

In both cases you reach the innest "if" block if and only if every previous "if" condition is true.

Don't be fooled by a long "if" condition with a bunch of &&: as soon as the first && is false, the execution skips outside the "if" (the remaining && in the single long condition are not evaluated).

Cheers,
Giovanni


SCJP 1.4
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Correct. && and || are shortcut operators - once the total result will already be known (e.g. if any operand is false for && or true for ||) it will ignore everything that follows. If you need to evaluate those always you should use & and |.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
rachana ravali
Ranch Hand

Joined: Jun 20, 2006
Posts: 32
Thanks Giovanni and Rob.
 
Consider Paul's rocket mass heater.
 
subject: writing If blocks