Possible Duplicate:
Does java evaluate remaining conditions after boolean result is known
Why do we usually use||not|, what is the difference?
I missed my class lecture the other day and I was wondering if anyone could give an explanation what short circuiting is and maybe an example of it being used in a simple Java program. Thanks for your help!
Short-circuiting is where an expression is stopped being evaluated as soon as its outcome is determined. So for instance:
If
a == bis true, thenc == dande == fare never evaluated at all, because the expression’s outcome has already been determined. ifa == bis false, thenc == dis evaluated; if it’s true, thene == fis never evaluated. This may not seem to make any difference, but consider:If
foo()returns true, thenbarandbazare never called, because the expression’s outcome has already been determined. So ifbarorbazhas some other effect than just returning something (a side effect), those effects never occur.One great example of short-circuiting relates to object references:
a.getFoo()would normally throw aNullPointerExceptionifawerenull, but because the expression short-circuits, ifa != nullisfalse, thea.getFoo()part never happens, so we don’t get an exception.Note that not all expressions are short-circuited. The
||and&&operators are short-circuited, but|and&are not, nor are*or/; in fact most operators are not.