• Post Reply Bookmark Topic Watch Topic
  • New Topic

Short-Circuit Logical Operator!!!

 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
what are the particular situatios that short-circuit logical operator (|| and &&) is used against other logical operators(| and &)? please help me with it.
thanks.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Namaste Sathi:
hi,
what are the particular situatios that short-circuit logical operator (|| and &&) is used against other logical operators(| and &)? please help me with it.
thanks.

The short circuit operators can save you from things like NullPointerExceptions and can cause a statement to only be evaluated if both operands are tested. For example:

That will save you from a runtime exception because if obj is null then obj.hashCode() will not be called which would result in a NullPointerException being thrown. Also consider this:

If the result of a + b is 6 then the statement c = c + 3 will not be evaluated so in that case c would not change.
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!