Does Java have lazy evaluation?

m0skit0 picture m0skit0 · Mar 3, 2013 · Viewed 36.2k times · Source

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?

Answer

emesx picture emesx · Mar 3, 2013

Well, as far as the language is concerned - yes, both functions are called.

If you rewrote the function to this:

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

then the second function will not be called, if the first is true.


But this is short-circuit evaluation, not lazy evaluation. Lazy evaluation case would look something like this:

public interface LazyBoolean {
    boolean eval();
}

class CostlyComparison implements LazyBoolean {
  private int a, b;

  public CostlyComparison(int a, int b) { 
    this.a=a; 
    this.b=b; 
  }

  @Override 
  public boolean eval() {
    //lots of probably not-always-necessary computation here
    return a > b;
  }
} 

public LazyBoolean isATrue() {
  return new CostlyComparison(10,30);  //just an example
}

public boolean isTrue() {        // so now we only pay for creation of 2 objects
    LazyBoolean a = isATrue();   // but the computation is not performed; 
    LazyBoolean b = isBTrue();   // instead, it's encapsulated in a LazyBoolean
    return b.eval() || a.eval(); // and will be evaluated on demand;
                                 // this is the definition of lazy eval.
}