AP Computer Science A · Topic 4.3
Developing Algorithms Using Strings Practice
Part of Iteration.
Practice questions
19
Sample questions
5 of 19 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
for (String s : list) { System.out.println(s); }Which traditional loop is equivalent for an ArrayList<String> list?
- A
for (int i = 0; i < list.size(); i++) System.out.println(list[i]);
- Bcheck_circle
for (int i = 0; i < list.size(); i++) System.out.println(list.get(i));
- C
for (int i = 0; i < list.length; i++) System.out.println(list.get(i));
- D
for (int i = 1; i <= list.size(); i++) System.out.println(list.get(i));
Why
ArrayList exposes size() and get(i); the indexed loop must use both for the same elements in order.
- A
Sample 2difficulty 2/5
String s = "hello"; String r = ""; for (int i = s.length() - 1; i >= 0; i--) { r += s.charAt(i); }What is r?
- A
hellohello
- Bcheck_circle
olleh
- C
hello
- D
(empty)
Why
The loop appends chars in reverse, producing "olleh".
- A
Sample 3difficulty 2/5
String s = "Java"; StringBuilder sb = new StringBuilder(s); String r = sb.reverse().toString();What is r?
- A
JAVa
- Bcheck_circle
avaJ
- C
ajva
- D
Java
Why
StringBuilder.reverse() reverses the character order.
- A
Sample 4difficulty 2/5
public static boolean isAna(String a, String b) { if (a.length() != b.length()) return false; char[] ca = a.toCharArray(); char[] cb = b.toCharArray(); java.util.Arrays.sort(ca); java.util.Arrays.sort(cb); return java.util.Arrays.equals(ca, cb); } // call: isAna("ab", "abc")What does it return?
- A
null
- Bcheck_circle
false
- C
true
- D
compile error
Why
Different lengths can't be anagrams; returns false immediately.
- A
Sample 5difficulty 3/5
public static boolean isPal(String s) { int i = 0, j = s.length() - 1; while (i < j) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } // call: isPal("hello")What does isPal("hello") return?
- A
0
- B
exception
- C
true
- Dcheck_circle
false
Why
'h' != 'o', so the function returns false.
- A