Unit 3: Boolean Expressions and if Statements

This unit introduces Boolean logic, conditional statements, and decision-making in Java.

Key Concepts

  • Boolean Expressions: Expressions that evaluate to true or false.
  • Relational Operators: ==, !=, <, >, <=, >=.
  • Logical Operators: && (AND), || (OR), ! (NOT).
  • Conditional Statements: if, else if, else.
  • Nested Conditionals: Using conditionals inside other conditionals.
  • De Morgan's Laws: Rules for simplifying logical expressions.

Example Code: Basic Boolean Expressions


// Example: Boolean Expressions and if Statements
public class BooleanExample {
  public static void main(String[] args) {
    int age = 18;
    boolean isStudent = true;

    // Boolean expression with relational and logical operators
    if (age >= 18 && isStudent) {
      System.out.println("You are an adult student.");
    } else if (age >= 18 || isStudent) {
      System.out.println("You are either an adult or a student.");
    } else {
      System.out.println("You are neither an adult nor a student.");
    }

    // Nested conditionals
    if (age > 16) {
      if (isStudent) {
        System.out.println("You are a student above 16.");
      } else {
        System.out.println("You are above 16 but not a student.");
      }
    }
  }
}
              

Example Code: Advanced Boolean Expressions


// Example: Advanced Boolean Expressions and Complex Conditionals
public class AdvancedBooleanExample {
    public static void main(String[] args) {
        // Complex boolean expressions
        int score = 85;
        boolean isPassing = score >= 60;
        boolean isHonors = score >= 90;
        boolean hasPerfectAttendance = true;
        
        // Using De Morgan's Laws
        boolean notPassing = !isPassing;
        boolean notHonors = !isHonors;
        
        // Complex conditional logic
        if (isHonors && hasPerfectAttendance) {
            System.out.println("Student qualifies for highest honors!");
        } else if (isPassing && hasPerfectAttendance) {
            System.out.println("Student qualifies for attendance award.");
        } else if (isPassing) {
            System.out.println("Student is passing.");
        } else {
            System.out.println("Student needs improvement.");
        }
        
        // Ternary operator example
        String grade = isHonors ? "A" : (isPassing ? "C" : "F");
        
        // Short-circuit evaluation
        boolean result = isPassing || (score > 100); // Second condition never evaluated if isPassing is true
        
        // Print results
        System.out.println("Grade: " + grade);
        System.out.println("Short-circuit result: " + result);
    }
}
              

Boolean Expressions and Logical Operators

Common Boolean Operators:

Operator Description Example
&& Logical AND true && false → false
|| Logical OR true || false → true
! Logical NOT !true → false
== Equality 5 == 5 → true
!= Not equal 5 != 3 → true

Boolean Expression Examples:


// Basic boolean expressions
boolean isAdult = age >= 18;
boolean isTeenager = age >= 13 && age <= 19;
boolean isChild = age < 13;

// Complex boolean expressions
boolean canVote = age >= 18 && isCitizen;
boolean canDrive = age >= 16 || hasSpecialPermit;
boolean isWeekend = day == "Saturday" || day == "Sunday";

// Using NOT operator
boolean isNotAdult = !isAdult;
boolean isNotWeekend = !isWeekend;
              

Short-Circuit Evaluation:


// && short-circuits if first condition is false
if (x != 0 && y / x > 2) {
    // Safe division because x != 0 is checked first
}

// || short-circuits if first condition is true
if (name == null || name.length() == 0) {
    // Safe length check because null is checked first
}
              

Boolean Expression Tips:

  • Use parentheses to clarify complex expressions
  • Take advantage of short-circuit evaluation
  • Use meaningful variable names for boolean values
  • Consider De Morgan's Laws for simplifying expressions
  • Be careful with floating-point comparisons

Common Pitfalls and Debugging Tips

Common Mistakes:

  • Assignment vs. Comparison: Using = instead of ==
    
    if (x = 5) {  // Wrong! Assigns 5 to x
    if (x == 5) { // Correct! Compares x with 5
                      
  • Floating-Point Comparison: Using == with doubles
    
    double x = 0.1 + 0.2;
    if (x == 0.3) {  // Wrong! Might be false due to precision
    if (Math.abs(x - 0.3) < 0.0001) {  // Correct! Uses tolerance
                      
  • String Comparison: Using == instead of equals()
    
    String s1 = "Hello";
    String s2 = new String("Hello");
    if (s1 == s2) {  // Wrong! Compares references
    if (s1.equals(s2)) {  // Correct! Compares content
                      

Debugging Tips:

  • Use System.out.println() to print boolean values
  • Break complex expressions into smaller parts
  • Use parentheses to clarify operator precedence
  • Test edge cases (null, zero, empty strings)
  • Use truth tables to verify complex logic

AP Exam Tips:

  • Know operator precedence rules
  • Understand short-circuit evaluation
  • Be able to evaluate complex boolean expressions
  • Know when to use equals() vs ==
  • Understand De Morgan's Laws

AP Exam-Style Practice Problems

Problem 1: Boolean Expression Evaluation

Consider the following code segment:


int x = 5;
int y = 10;
boolean result = (x > 3) && (y < 15) || (x + y == 20);
System.out.println(result);
                

What is printed as a result of executing the code segment?

true
false
The correct answer is A. The expression evaluates to true because (x > 3) is true and (y < 15) is true, making the entire expression true.
Problem 2: Short-Circuit Evaluation

Consider the following code segment:


int x = 0;
boolean result = (x != 0) && (10 / x > 2);
System.out.println(result);
                

What is printed as a result of executing the code segment?

true
false
ArithmeticException
The correct answer is B. Due to short-circuit evaluation, the second part of the expression is not evaluated because x != 0 is false.
Problem 3: String Comparison

Consider the following code segment:


String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
                

What is printed as a result of executing the code segment?

false true
true true
false false
true false
The correct answer is A. s1 and s2 are different objects (false), but they have the same content (true).
Problem 4: Complex Boolean Expression

Consider the following code segment:


int age = 16;
boolean hasLicense = true;
boolean hasParent = false;
boolean canDrive = (age >= 16 && hasLicense) || (age >= 15 && hasParent);
System.out.println(canDrive);
                

What is printed as a result of executing the code segment?

true
false
The correct answer is A. The expression evaluates to true because age >= 16 is true and hasLicense is true.

Multiple Choice Practice

Question 1:

What is the output of the following code?


int x = 5;
int y = 10;
System.out.println(x > 3 && y < 20);
              
A. true
B. false
C. 15
D. Error
E. None of the above
Explanation: The answer is A. The expression x > 3 evaluates to true (5 > 3) and y < 20 evaluates to true (10 < 20). When using the && operator, both conditions must be true for the result to be true.

Question 2:

Which of the following is true about logical operators in Java?

A. && evaluates to true if both operands are true
B. || evaluates to true if at least one operand is true
C. ! inverts the value of a Boolean expression
D. All of the above
E. None of the above
Explanation: The answer is D. All of the statements about logical operators are true. The && operator requires both operands to be true, || requires at least one operand to be true, and ! inverts the value of a Boolean expression.

Question 3:

What is the result of the following code?


boolean a = true;
boolean b = false;
boolean c = true;
System.out.println(a && b || c);
              
A. true
B. false
C. Error
D. 1
E. 0
Explanation: The answer is B. The expression is evaluated as (a && b) || c. First, a && b evaluates to false (true && false = false). Then, false || c evaluates to false (false || true = true).

Question 4:

Which of the following is NOT a valid boolean expression in Java?

A. x > 5 && y < 10
B. !(a || b)
C. x + y = 15
D. isTrue == true
E. count != 0
Explanation: The answer is C. The expression x + y = 15 is invalid because it uses a single = which is the assignment operator. For comparison, you should use == instead of =.

Question 5:

What is the value of the following expression?


!(true && false) || (true && true)
              
A. false
C. true
C. Error
D. 1
E. 0
Explanation: The answer is B. Let's evaluate step by step: 1) true && false = false, 2) !false = true, 3) true && true = true, 4) true || true = true.

Practice Problems

  1. Write a program that checks if a number is positive, negative, or zero.
  2. Write a program that determines if a year is a leap year.
  3. Write a program that checks if a user is eligible to vote (age >= 18).
  4. Write a program that uses nested conditionals to determine the grade based on a score.
  5. Write a program that checks if a number is divisible by both 3 and 5.
  6. Create a program that determines if a triangle is valid based on its side lengths.
  7. Write a program that checks if a string is a palindrome using boolean expressions.
  8. Create a program that determines if a number is prime using boolean logic.

Tips for Success

  • Understand the difference between relational and logical operators.
  • Practice writing and evaluating Boolean expressions.
  • Use parentheses to clarify the order of operations in complex expressions.
  • Test your conditionals with different inputs to ensure they work as expected.
  • Learn De Morgan's Laws to simplify logical expressions.
  • Be careful with the order of operations in complex boolean expressions.
  • Use meaningful variable names for boolean values (e.g., isPassing, hasPermission).
  • Remember that && has higher precedence than ||.

Interactive Code Playground

Try out your own boolean expressions and conditional statements here!

Output:
Note: This is a simulated environment. For actual Java code execution, please use an IDE or online Java compiler.

For actual code execution, we recommend using:

Test Your Knowledge

1. What is the result of the expression: !(true && false) || true?
true
false
Compilation error
Runtime error
The correct answer is A. true. The expression evaluates as follows: !(true && false) || true → !(false) || true → true || true → true.
2. Which of the following is NOT a valid boolean expression?
x > 5 && y < 10
x = 5 || y = 10
!(x == y)
x >= 0 && x <= 100
The correct answer is B. x = 5 || y = 10. This is not valid because = is the assignment operator, not a comparison operator. The correct comparison operators are ==, !=, >, <, >=, <=.
3. What is the result of the expression: (5 > 3) ? "Yes" : "No"?
"Yes"
"No"
true
false
The correct answer is A. "Yes". This is a ternary operator expression. Since 5 > 3 is true, it returns the first value "Yes".