Which of the following would return the last character of the String x?


Which of the following would return the last character of the String x?


a) x.charAt(0);

b) x.charAt(last);

c) x.charAt(length(x));

d) x.charAt(x.length( )-1);

e) x.charAt(x.length( ));

Answer: d. Explanation: Since last is not defined, b is syntactically invalid. The 0th character is the first in the String, so a is true only if the String has a single character. The answer in c is syntactically invalid as length can only be called by passing the message to x. Finally, d and e are syntactically valid, but since length returns the size of the String, and since the first character starts at the 0th position, the last character is at x.length()-1, so e would result in a run-time error.