Does Java have lazy evaluation?

后端 未结 9 1580
面向向阳花
面向向阳花 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:38

    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.

提交回复
热议问题