AP Computer Science A · Topic 4.3

Developing Algorithms Using Strings Practice

Part of Iteration.

Practice questions

19

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 19 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. 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]);

    • B

      for (int i = 0; i < list.size(); i++) System.out.println(list.get(i));

      check_circle
    • 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.

  2. 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

    • B

      olleh

      check_circle
    • C

      hello

    • D

      (empty)

    Why

    The loop appends chars in reverse, producing "olleh".

  3. Sample 3difficulty 2/5

    String s = "Java";
    StringBuilder sb = new StringBuilder(s);
    String r = sb.reverse().toString();

    What is r?

    • A

      JAVa

    • B

      avaJ

      check_circle
    • C

      ajva

    • D

      Java

    Why

    StringBuilder.reverse() reverses the character order.

  4. 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

    • B

      false

      check_circle
    • C

      true

    • D

      compile error

    Why

    Different lengths can't be anagrams; returns false immediately.

  5. 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

    • D

      false

      check_circle

    Why

    'h' != 'o', so the function returns false.