
public class Palin {

  public static void main (String[] args) {

  // middle returns a substring that includes all but the
  // first and last; only works if s has at least two characters
  public static String middle (String s) {
    int length = s.length();
    return s.substring (1, length-1);
  }

  // first returns the first character of a string
  // first only works if s has at least one characters
  public static char first (String s) {
    return s.charAt (0);
  }

  // last returns the last character of a string
  // last only works if s has at least one characters
  public static char last (String s) {
    int len = s.length();
    return s.charAt (len - 1);
  }

  // tail returns all but the last two characters of the
  // String.  it is completely bulletproof; there are no
  // preconditions.  
  public static String tail (String s) {
    if (s == null) return "";
    int len = s.length();
    if (len == 0 || len == 1) {
      return "";
    }
    return s.substring (2, len);
  }

  public static boolean isPalindrome (String s) {
    int len = s.length();
    if (len == 0 || len == 1) {
      return true;
    }

    // at this point we know that len>=2, so it is safe
    // to invoke first, last, and middle

    if (first(s) != last(s)) {
      return false;
    } else {
      boolean recurse = isPalindrome (middle (s));
      return recurse;
    }
  }

  public static boolean hasComma (String s) {
    int index = s.indexOf(',');
    return (index != -1);
  }

  public static String convertName (String s) {
    if (hasComma (s)) {
      return s;
    }
    int space = s.indexOf(' ');
    int len = s.length();
    String first = s.substring (0, space);
    String last = s.substring (space+1, len);
    return last + ", " + first;
  }
}
