wood burning stoves*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 19651
    
  18

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: writing If blocks
 
Similar Threads
Does your company require documentation? If so, what kind?
State machine quick question
Doubt in Java coding standard
condition to leave all your loops
Question about boolean short circuit