AP CSA String Manipulation and 2D Arrays 1 — Questions and Answers
Question 1: Which method returns the number of characters in a String in Java?
- length() (Correct answer)
- size()
- count()
- charAt()
Correct answer: length()
The String.length() method returns the number of characters (including spaces) in the string.
Question 2: What does `str.substring(2, 5)` return for `str = "ABCDEFG"`?
- "CDE" (Correct answer)
- "BCD"
- "CDEF"
- "BCDE"
Correct answer: "CDE"
substring(2,5) returns characters from index 2 up to but not including index 5, giving 'C','D','E' → "CDE".
Question 3: What does `str.charAt(0)` return for `str = "Hello"`?
- 'H' (Correct answer)
- 'e'
- "H"
- 0
Correct answer: 'H'
charAt(0) returns the char at index 0, which is 'H' — a primitive char, not a String.
Question 4: How do you compare two Strings for equal content in Java?
- str1.equals(str2) (Correct answer)
- str1 == str2
- str1.compareTo(str2) == 0 (also valid but equals is standard)
- str1.equalsTo(str2)
Correct answer: str1.equals(str2)
The equals() method compares String content; using == compares object references, which may give unexpected results for Strings.
Question 5: What does `str.indexOf("lo")` return for `str = "Hello"`?
- 3 (Correct answer)
- 2
- 0
- -1
Correct answer: 3
indexOf returns the starting index of the first occurrence of the substring; "lo" starts at index 3 in "Hello".
Question 6: What is the result of `"Hello" + " " + "World"`?
- "Hello World" (Correct answer)
- "HelloWorld"
- A compile error
- "Hello" " " "World"
Correct answer: "Hello World"
The + operator concatenates Strings in Java, combining "Hello", " ", and "World" into "Hello World".
Which method returns the number of characters in a String in Java?