?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

String Comparisons in ArrayList of Strings

APCSA-PFNGYG

Consider the following method.

public static int mathString(ArrayList<String> words)
{
    int num = 0;
    for (int i=0; i<words.size(); i++)
    {
        String a = words.get(i).substring(0.1);
        String b = words.get(i).substring(words.get(i).length()-1);

        if (a.compareTo(b)<0)
            num-=words.get(i).length();
        else
        if (a.compareTo(b)>0)
            num+=words.get(i).length();
     }
     return num;
}

What is the output from the following segment of code?

    ArrayList<String> words = new ArrayList<String>();
    words.add("dragon");
    words.add("snakes");
    words.add("worm");
    words.add("pup");
    words.add("antelope");
    words.add("toad");
    System.out.println(mathString(words));
A

-6

B

-3

C

0

D

3

E

6