• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

writing If blocks

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 22853
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Giovanni and Rob.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic