Limited access

Upgrade to access all content for this subject

Consider the following method.

public static String getLastLetter(String phrase)
{
    for (int i=0; i<phrase.length(); i++)
    {
        if ( i == phrase.length()-1)
            return phrase.substring(i);
    }
    return "?";
}

How could this method be rewritten to make it more efficient and still have an equivalent result?

Choose the BEST option from the methods presented.

A
public static String getLastLetter(String phrase)
{
    if (phrase.length() == 0)
        return “?”;
    for (int i=0; i<phrase.length(); i++)
    {
        if (i == phrase.length()-1)
            return phrase.substring(i);
    }
}
B
public static String getLastLetter(String phrase)
{
    if ( phrase.length() == 0)
         return “?”;
    return phrase.substring(phrase.length()-1);            
}
C
public static String getLastLetter(String phrase)
{
    String str = “”;
    for (int i=0; i<phrase.length(); i++)
    {
        if (i < phrase.length()-1)
            str += ””;
        else
            str += phrase.substring(i, i+1);
    }
    return str;            
}
D
public static String getLastLetter(String phrase)
{
    for (int i=0; i<phrase.length(); i++)
    {
        if (i == phrase.length()-1 )
            return phrase.substring(i, i+1);
    }
    return “?”;     
}
E
public static String getLastLetter(String phrase)
{
    for (int i=0; i<phrase.length(); i++)
    {
        if (i == 0)
            return return “?”;
    }
    return phrase.substring(i, i+1);
}
Select an assignment template