If you see a code below, what would you guess the output is?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ShortCircuit { | |
private static boolean funcReturningTrue () { | |
System.out.println ("this function returns true"); | |
return true; | |
} | |
private static boolean funcReturningFalse () { | |
System.out.println ("this function returns false"); | |
return false; | |
} | |
public static void main (String[] args) { | |
if (funcReturningTrue() || funcReturningFalse()) | |
System.out.println ("eval 1 complete"); | |
if (funcReturningFalse() && funcReturningTrue()) | |
; | |
else | |
System.out.println ("eval 2 complete"); | |
boolean bool = (true) ? funcReturningTrue() : funcReturningFalse(); | |
System.out.println ("bool = " + bool); | |
} | |
} |
Similarly, (false && bool) is false regardless of bool, so again bool will not be evaluated. This corresponds to the 2nd if statement in the code above.
Lastly, the statement (condition) ? a : b will evaluate only a or b but not both depending on the condition. If one were to make sure that both conditions to be evaluated in the examples above, one should use | and & in place of || and &&.
Now, one can easily predict the output of the program above:
this function returns true
eval 1 complete
this function returns false
eval 2 complete
this function returns true
bool = true
No comments:
Post a Comment