Problem of the Day
Problem:
Consider the following method.
public static String tryThis(String s)
{
s = s.substring(s.length() - 1) + s.substring(0,s.length() - 1);
System.out.print(s);
return s;
}
Which of the following is printed as a result of executing the following statements?
String s1 = "abcde";
tryThis(s1);
System.out.print(s1);
eabcdabcde
abcdeabcde
eabcdeabcd
abcdeeabcd
The correct answer is a. The static method tryThis
takes the string argument sent in and creates a new String with the last character moved to the front of the String, and sets s
to that new String value. That new value is printed, and returned by the method to the caller, but that returned value isn't set to any variable. The caller's s1
variable retains its original reference to "abcde"
, resulting in the output from choice (a).
This is a bit of a trick question—why would we have a method return a value, and then the caller doesn't do anything with that value? There are situations where a method is called but nothing is done with the return value—popping from a stack, for example—but in this case, the question is just trying to be obtuse.