Unit 2 Cycle 2 Day 15: Compound Condition with String Methods
Share
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.
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.