Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
m0skit0 Avatar asked Mar 03 '13 18:03

m0skit0


People also ask

Are Java streams lazy?

Streams are lazy because intermediate operations are not evaluated unless terminal operation is invoked. Each intermediate operation creates a new stream, stores the provided operation/function and return the new stream.

What is lazily evaluated in Java?

Lazy evaluation Represents a supplier of results. There is no requirement that a new or distinct result be returned each time the supplier is invoked. This is a functional interface whose functional method is get().

What programming languages support lazy evaluation?

Languages that support lazy evaluation are usually functional programming languages like Haskell, which is lazy by default. Some languages, like OCaml and Scheme, let you opt into lazy behavior. Other languages like Swift and Perl 6 support it only for lists.

What is lazy in Java?

Lazy class loading is an important feature of the Java runtime environment as it can reduce memory usage under certain circumstances. For example, if a part of a program never is executed during a session, classes referenced only in that part of the program never will be loaded.


1 Answers

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. } 
like image 59
emesx Avatar answered Oct 04 '22 15:10

emesx