Does Java have lazy evaluation?

后端 未结 9 1574
面向向阳花
面向向阳花 2020-12-03 16:44

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

public boolean isTrue() {
    boolean a = false;
    boolean b = true;
    return b || (a &&         


        
9条回答
  •  粉色の甜心
    2020-12-03 17:28

    Just wanted to add in addition to what have been mentioned in this question thread, below is from Oracle Documentation on JVM

    a Java Virtual Machine implementation may choose to resolve each symbolic reference in a class or interface individually when it is used ("lazy" or "late" resolution), or to resolve them all at once when the class is being verified ("eager" or "static" resolution). This means that the resolution process may continue, in some implementations, after a class or interface has been initialized.

    reference

    and as an example of the classes that has lazy implementation is Stream, this is from Oracle Documentation on Stream

    Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

    reference

    That being said, if you do the following, nothing will be displayed. Unless you add initiator.

    Steam.of(1, 2, 3, 4, 5).filter(number -> {
       System.out.println("This is not going to be logged");
       return true;
    });
    

提交回复
热议问题