Task 7 of 10 · 0 solved · 10 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

1.6 Logic — short-circuit evaluation

Lesson

Java stops as soon as it knows

When Java evaluates a && b and a is already false, the whole thing is false whatever b is — so b is never evaluated at all. The same for a || b: if a is true, Java stops. This is called short-circuit evaluation.


Worked example

int n = 0;
System.out.println(n != 0 && 10 / n > 1);   // false — and no crash

Look closely: 10 / n is division by zero, which crashes a program. It does not crash here, because n != 0 is false and Java never reaches the division.

That is the practical use: put the guard first, and the dangerous test second. Swap them and the program dies.


▶ Try it: run this, then change something and run it again.



In a && b, when is b skipped?


In a || b, when is b skipped?


Type exactly what this program prints.

public class Main { public static void main(String[] x){
    int n = 0;
    System.out.println(n > 0 && 100 / n > 5);
    System.out.println(n == 0 || 100 / n > 5);
}}

Why does n != 0 && 10 / n > 1 not crash when n is 0?


True or false?