Unit 1 Cycle 1 Day 26: Objects, Methods, and Return Types
Share
Objects, Methods, and Return Types
Section Mixed — Review: Objects and Methods
Key Concept
The AP CSA exam frequently combines multiple concepts in a single problem: type casting with string concatenation, method calls inside arithmetic expressions, or boolean logic with method return values. When tracing these combined expressions, follow Java's evaluation rules strictly: parentheses first, then operator precedence, then left-to-right for equal precedence. A methodical approach is to evaluate innermost expressions first and work outward. Watch for implicit conversions — adding an int to a String triggers string concatenation, not addition.
Consider the following method.
What is returned by the call convert(185)?
Answer: (A) "3:05"
Substitute totalSeconds = 185:
min: 185 / 60 = 3 (integer division).
sec: 185 % 60 = 5 (remainder: 3 * 60 = 180, 185 - 180 = 5).
Ternary: sec < 10 is 5 < 10 = true, so the ternary returns "0".
Concatenation: 3 + ":" + "0" + 5 = "3:05".
Why Not the Others?
(B) The ternary operator adds a leading zero when sec < 10. Since sec = 5, the "0" prefix is included, making it "05" not "5".
(C) The separator is a colon ":", not a period. Look carefully at the string literal in the return statement.
(D) The ternary produces either "0" or "" (empty string). When sec < 10, it adds "0", then concatenates sec (which is 5). Result: "0" + 5 = "05", not "085".
Common Mistake
The ternary operator condition ? valueIfTrue : valueIfFalse is a compact if-else. Here it pads single-digit seconds with a leading zero. Once the "0" string appears in the concatenation chain, subsequent + operations are string concatenation.
AP Exam Tip
The ternary operator appears on the AP exam. Read it as: if the condition is true, use the first value; otherwise, use the second. It is equivalent to an if-else but written in a single expression.