• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

writing If blocks

 
rachana ravali
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 |.
 
rachana ravali
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Giovanni and Rob.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic