Friday 22 July 2011

Senior Java Developer Test

Found the following test on http://thedailywtf.com. It tickled my fancy. An interesting use for recursion.

Question 1
(a) What does the following function do?
(b) How could the function be improved?
(c) Rewrite the function with your suggested improvements.
public String funcX (String s) {
  if (s == null || s.length() == 1 || s.length() == 0) {
    return s;
  } else {
    return funcX(s.substring(1)) + s.substring(0, 1);
  }
}

Just a small javadoc addendum to clarify things:

public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

3 comments:

  1. public String funcX (String s) {
    return aString != null && aString.length() != 1 | aString.length() != 0 ? new StringBuffer(aString).reverse()
    .toString() : null;
    }

    ReplyDelete
    Replies
    1. Correct!

      It is basically a really complicated form of Stringbuffer.reverse.

      Delete
  2. I have also put up a java developer test with scoring assessment. let me know how you find it.

    ReplyDelete