Skip to main content

Learning about Code Structure

Section 1.10 Rule 2) Directly return boolean expressions

Please watch the video to learn about the second rule (directly returning boolean conditions) and then answer the following question. Enlarge the window to view the code examples clearly. If necessary, click the settings icon in the video player and set the quality to 1080p for better clarity.
Figure 1.10.1. Directly return boolean expressions part 1

Activity 1.10.1.

    To which of the following code blocks can we apply Rule 2?
  • if (condition1) {
       return false; 
    }
    if (condition2) {
       return false; 
    }
    return true;
    
  • We can conjoin the if conditions together using || and then we have an if statement that always returns true in some senarios and false in other senarios. So, we can apply rule 2 and directly return the negation of conjoined conditions. (In the next video you will see how)
  • if (condition1) {
       return false; 
    }
    
  • No, the if statement only returns false.
  • boolean flag = true;
    if (condition1 && condition2 || condition3) {
       return flag; 
    }
    return false;
    
  • Yes. the if condition returns boolean variable true when the condition evaluates to true and returns false otherwise. So, we can apply rule 2 and directly return the if condition.

Checkpoint 1.10.2.

The function areStringsEqual() takes two String inputs and returns a boolean. Complete the function by filling in the blanks so that when the two Strings are the same it returns true. Otherwise, it returns false. You can compare String values using equals() method.
public static boolean areStringsEqual(String str1, String str2) {   
   return .......Blank......... ; 
}
Write your responses here:
Blank:
You have attempted 1 of 4 activities on this page.