Unit 2 Cycle 2 Day 15: Compound Condition with String Methods

Unit 2 Advanced (Cycle 2) Day 15 of 28 Advanced

Compound Condition with String Methods

Section Mixed — Review: Booleans and Strings

Key Concept

When compound boolean conditions include String method calls, you must evaluate the method calls within the boolean context. For example, str.length() > 3 && str.substring(0, 3).equals("abc") uses short-circuit evaluation to avoid a potential StringIndexOutOfBoundsException. If the string is shorter than 3 characters, the first condition is false and the substring call is skipped. The AP exam tests whether you recognize these protective patterns and understand what happens if the conditions are reordered.

Consider the following code segment.

String s = "Hello World"; boolean r = s.length() > 5 && s.indexOf(" ") > 0 && s.substring(0, 1).equals("H");

What is the value of r?

Answer: (A) true

s.length() > 5: 11 > 5 is true. s.indexOf(" ") > 0: 5 > 0 is true. s.substring(0,1).equals("H"): "H".equals("H") is true. All three are true, so true && true && true = true.

Why Not the Others?

(B) All three conditions evaluate to true.

(C) The code is syntactically valid. Long expressions can be split across lines.

(D) No null values or out-of-bounds accesses occur.

Common Mistake

Chained && conditions all must be true for the result to be true. Evaluate each part independently. If any part is false, the entire expression is false (and short-circuits).

AP Exam Tip

Break down complex boolean expressions into parts. Evaluate each sub-expression, then combine with the logical operators.

Review this topic: Section Mixed — Review: Booleans and Strings • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.