MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
  • Unit 2: Selection and Iteration
    • Part 1: Selection
      • Algorithms with Selection and Repetition
      • Boolean Expressions
      • if Statements
      • Nested if Statements
      • Compound Boolean Expressions
      • Comparing Boolean Expressions
      • Unit 2 Part 1 Slides
    • Part 2: Iteration
  • Unit 3: Class Creation
  • Unit 4: Data Collections

Unit 2.5: Compound Boolean Expressions

Logical Operators

Logical operators combine boolean expressions.

Compound Logic
  • Logical operators allow you to create complex conditions by joining multiple Boolean expressions. They evaluate to a single true or false result.
Operator Name Description
! NOT Inverts the value (!true is false).
&& AND True only if both operands are true.
|| OR True if at least one operand is true.

Truth Tables

A B !A A && B A || B
true true false true true
true false false false true
false true true false true
false false true false false

Short-Circuit Evaluation

  • AND (&&): If the first operand is false, the result is false immediately. The second operand is not evaluated.
  • OR (||): If the first operand is true, the result is true immediately. The second operand is not evaluated.

Examples

Using Logical Operators

Task: Applying compound boolean logic and short-circuit protection.

public class LogicExample {
    public static void main(String[] args) {
        int age = 15;
    boolean hasLicense = false;
    
    // AND example
    if (age >= 16 && hasLicense) {
        System.out.println("Can drive");
    } else {
        System.out.println("Cannot drive");
    }
    
    // OR example
    boolean hasCash = false;
    boolean hasCredit = true;
    if (hasCash || hasCredit) {
        System.out.println("Can pay");
    }
    
    // Short-circuit protection against divide by zero
    int count = 0;
    int total = 100;
    
    // If count is 0, the second part (total / count) is skipped
    if (count != 0 && (total / count > 10)) {
        System.out.println("Valid average");
    } else {
        System.out.println("Cannot calculate");
    }
}

}


Privacy Policy | Terms & Conditions