Learn AP Comp Sci

Problem of the Day

Thursday, May 14, 2026


Problem:

The letterWords method is intended to take as parameters an Array of Strings, words, and a String value letter, and return an ArrayList containing only the Strings in words that begin with the specified letter. The Array {"apple", "banana", "carrot", "avocado"}, sent in as an argument along with "a" as the argument for letter would return an ArrayList containing only "apple", "avocado".

A partial listing of the letterWords method is given here.

public static ArrayList<String> letterWords(String[] words, String letter)
{
ArrayList<String> result = new ArrayList<String>();

/* missing code */

return result;
}

Which of the following could be used to replace /* missing code */ so the method works as intended?


  1. for (int i = 0; i < words.length; i++)
    if (words[i].substring(i, i + 1).equals(letter))
    result.add(words[i]);

  2. for (int i = 0; i < words.length; i++)
    if (words[i].substring(0, 1).equals(letter))
    result.add(words[i]);

  3. for (String word : words)
    if (word.substring(0, 1).equals(letter))
    result.add(word);
  1. I only
  2. II only
  3. III only
  4. I and II only
  5. II and III only

Show solution:

The correct answer is e. Both of these options correctly work their way through the list of words, checking to see if the initial letter of a word matches the letter given.