Skip to main content

Learning about Code Structure

Section 1.5 Rule 1) Conjoining Conditions

Continue watching the video to learn when to conjoin conditions with &&, then answer the following questions.
Figure 1.5.1. Conjoining conditions with && part 2

Activity 1.5.1.

    Consider the following Java function. What happens when the function is called with the given inputs print(3, 0, 0);?
    public static void print(int x, int y, int z) {
        if (x > 10 && x / y > 10 && z > 10) {
            System.out.println("Condition met");
        }
        System.out.println("End of program");
    }
    
  • The code first prints "Condition met" and then prints "End of program"
  • Since the first condition is false, the if condition is false and the program skips its body.
  • The code only prints "End of program"
  • The first condition x > 10 is false, so the short-circuit evaluation prevents the execution of x / y > 10. This avoids a division by zero error. Therefore, only "End of program" is printed.
  • The code throws an error for division by zero
  • Since the first condition is false, the program does’t bother checking the rest of conjoined conditions and it evaluates the if condition as false.
  • Nothing will be printed

Activity 1.5.2.

    What happens when the function is called with these new inputs print(12, 0, 20);?
  • The code first prints "Condition met" and then prints "End of program"
  • Based on short circuit evaluation, the first condition is true, and the second one will be checked. The second condition will lead to an error.
  • The code only prints "End of program"
  • The code throws an error for division by zero
You have attempted 1 of 4 activities on this page.