Unit 1 Cycle 1 Day 16: length() and Extracting Characters
Share
length() and Extracting Characters
Section 1.10 — Strings: Methods
Key Concept
Calling methods on objects uses dot notation: obj.methodName(arguments). Methods can return values (non-void) or perform actions without returning (void). A non-void method must be used in an expression or assignment — its return value is lost if you call it as a standalone statement. Void methods cannot be used in expressions. The AP exam frequently tests whether a method call is valid: calling a non-static method requires an object reference, and the arguments must match the parameter types in the method signature.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) BY6
Index the string: B(0) I(1) N(2) A(3) R(4) Y(5)
first: substring(0, 1) = character at index 0 = "B".
last: s.length() = 6. substring(6 - 1) = substring(5) = everything from index 5 onward = "Y".
Output: "B" + "Y" + 6 = "BY6".
Why Not the Others?
(B) The last character is at index 5, which is 'Y', not 'R'. 'R' is at index 4 (the second-to-last character).
(C) The length of "BINARY" is 6, not 5. length() returns the total number of characters.
(D) Both the character and the length are wrong. The last character is 'Y' and the length is 6.
Common Mistake
A common error is confusing the last valid index with the length. For a 6-character string, the last index is 5 but length() returns 6. substring(s.length() - 1) correctly gets the last character.
AP Exam Tip
To get the last character of a String: s.substring(s.length() - 1). To get the first character: s.substring(0, 1). These patterns appear frequently on the AP exam.