Search code examples
javalazy-evaluation

Does Java have lazy evaluation?


I know that Java has smart/lazy evaluation in this case:

public boolean isTrue() {
    boolean a = false;
    boolean b = true;
    return b || (a && b); // (a && b) is not evaluated since b is true
}

But what about:

public boolean isTrue() {
    boolean a = isATrue();
    boolean b = isBTrue();
    return b || a;
}

Is isATrue() called even if isBTrue() returns true?


Solution

  • In Java (and other C-like languages), this is referred to as short-circuit evaluation.*

    And yes, in the second example isATrue is always called. That is, unless the compiler/JVM can determine that it has no observable side-effects, in which case it may choose to optimize, but in which case you wouldn't notice the difference anyway.


    * The two are quite distinct; the former is essentially an optimization technique, whereas the second is mandated by the language and can affect observable program behaviour.

    I originally suggested that this was quite distinct from lazy evaluation, but as @Ingo points out in comments below, that's a dubious assertion. One may view the short-circuit operators in Java as a very limited application of lazy evaluation.

    However, when functional languages mandate lazy-evaluation semantics, it's usually for a quite different reason, namely prevention of infinite (or at least, excessive) recursion.