From the free course AP Computer Science A on Lykke

2.2 Boolean Expressions

Key concepts: Boolean literals and return values · Logical AND operator (&&) · Logical NOT operator (!) · Relational and equality comparisons · Compound Boolean expressions · Short-circuit evaluation of Boolean conditions · Finding contiguous blocks through iteration · Tracking block length with a counter · Returning a sentinel value when no block is found · Common loop-structure and variable-initialization errors

A Boolean expression evaluates to exactly one of two values: true or false. That simple choice controls whether an algorithm accepts a match, continues searching, reserves time, or reports failure.

2.2 Boolean Expressions

A Boolean expression evaluates to exactly one of two values: true or false. That simple choice controls whether an algorithm accepts a match, continues searching, reserves time, or reports failure.

Boolean values and comparisons

A Boolean literal is the value true or false written directly in a program. Methods can also return Boolean values. For example, an algorithm that searches a puzzle for two compatible entries should return true when it finds and processes a valid pair, and return false after checking every possibility without finding one.

Relational operators compare numerical values:

  • <, <=, >, and >= compare relative size.
  • == tests whether two primitive values are equal.
  • != tests whether two values are different.

For example, duration <= 60 is true when the requested appointment lasts at most $60$ minutes. The expression i == row is true only when the two indices have the same value.

Key distinction: = assigns a value; == compares values. A Boolean condition needs a comparison such as i == row, not an assignment such as i = row.

Java does not support mathematical chained comparisons such as 1 <= period <= 8. Write the two comparisons separately and connect them with &&:

1 <= period && period <= 8

&&: logical AND

The logical AND operator, &&, produces true only when both expressions are true.

Consider the puzzle condition:

(puzzle[i][j] + val == 10) && !(i == row && j == col)

It has two required tests:

  1. puzzle[i][j] + val == 10 checks whether the two entries add to $10$.
  2. !(i == row && j == col) checks that the candidate is not the same position as the original entry.

The inner expression i == row && j == col is true only when both the row and column match. The ! operator negates that result, so it becomes false for the same position and true for a different position.

When both requirements succeed, the algorithm performs the successful update:

puzzle[i][j] = 0;
puzzle[row][col] = 0;
return true;

If the loops finish without a valid pair, the final return false; communicates that no match exists.

!: logical NOT

The logical NOT operator, !, reverses a Boolean value:

Expression Result
!true false
!false true

A common error is to read !(i == row && j == col) as “the row is different and the column is different.” That is too strong. It means “it is not true that both coordinates match,” so a candidate is allowed if either the row differs, the column differs, or both differ.

Compound conditions and short-circuit evaluation

A compound Boolean expression combines smaller Boolean expressions with operators such as &&, ||, and !. Java uses short-circuit evaluation: with A && B, Java evaluates B only if A is true, because the whole expression is already false when A is false.

This behavior is useful when the first test protects the second:

if (index >= 0 && values[index] == target)
{
    return true;
}

If index >= 0 is false, Java does not evaluate values[index], avoiding an invalid array access.

Worked example: finding a contiguous appointment

To reserve an appointment, an algorithm must find consecutive free minutes whose length equals duration. The variable blockLength counts the current uninterrupted run:

int blockLength = 0;

for (int minute = 0; minute < 60; minute++)
{
    if (isMinuteFree(period, minute))
    {
        blockLength++;
        if (blockLength == duration)
        {
            int startMin = minute - blockLength + 1;
            reserveBlock(period, startMin, duration);
            return startMin;
        }
    }
    else
    {
        blockLength = 0;
    }
}
return -1;

If a busy minute interrupts the run, blockLength resets to $0$. When it reaches duration, the starting minute is minute - blockLength + 1. If no valid block exists, -1 indicates failure.

A starting minute must leave enough room for the entire appointment. The boundary condition is:

$$ startMin < 60 - blockLength + 1 $$

Misconception check: while (i=0; i<=duration; i++) is not a counter-based Java loop. It uses assignment, includes for-loop syntax inside while, and does not examine all possible starting minutes. Initialize and update a counter in a correctly structured for or while loop.

Retrieval check

What must be true for (sum == 10) && !(sameRow && sameColumn) to be true? Why does blockLength reset when a minute is busy? Finally, identify the error in 1 <= period <= 8 and rewrite it as a valid Java Boolean expression.

2.2 Boolean Expressions - AP Computer Science A - image 1
2.2 Boolean Expressions - AP Computer Science A - image 1

Source Materials

The whole course on Lykke · Browse all public course wikis