File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Android Security Essentials Live Lessons this week in the Android 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: 19655
    
  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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
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