Short-Circuit Evaluation

Download Report

Transcript Short-Circuit Evaluation

Lazy Evaluation
Computer Science 3
Gerb
Objective: Understand lazy evaluation in Java
Short-Circuit Evaluation
• If the first operand of an && is false, the
expression is false no matter what the second is.
– Pointless even to look at it
– Therefore Java won’t look at the second operand of &&
if the first is false.
• Example:
if (method1() && method2()) ...
– If method1 returns false, method2 won’t even be called.
– Important if method2 has side effects like printing,
those side effects will not happen.
• This technique for evaluating && is called shortcircuit evaluation or lazy evaluation.
Short-Circuit Evaluation of ||
• If the first operand of || is true, the
expression is true no matter what the second
is.
• Therefore Java uses short-circuit evaluation
for || as well.
• If the first operand of || is true, the second is
never evaluated.
Why is Short Circuit Evaluation
Important
• When a method does something other than
returning a value, we call that a side effect
• Examples :
– Printing something to console
– Changing the value of an instance variable
– Onscreen graphics
• If a method is not called, its side effects
won’t happen
For Example: What happens if I
answer true to the first question?
class foo {
public static boolean ask(String q){
System.out.println(q+“?”);
return sc.nextBoolean();
}
public static void main(String args){
if (ask(“Are you over 17”)
|| ask(“Did you take Driver Ed”))
System.out.println(“Take driving test”);}
}
Will not even call ask a second time, so
the Driver Ed question won’t be asked
class foo {
public static boolean ask(String q){
System.out.println(q+”?”);
return sc.nextBoolean();
}
public static void main(String args){
if (ask(“Are you over 17”)
|| ask(“Did you take Driver Ed”))
System.out.println(“Take driving test”);}
}
Are you over 17?
true
Take driving test
Summary
• && true if both operands are true, false
otherwise.
• || false if both operands are false, true
otherwise.
• ! true if single operand is false, false
otherwise.
• Short-circuit, or lazy, evaluation
– Second operand is only evaluated if necessary.