Use
class Palindrome {
public static String reverse(String s) {
if ("".equals(s)) {
return s;
} else {
return reverse(s.substring(1,s.length())) + s.charAt(0);
}
}
public static void main(String args[]) {
System.out.print(reverse("galskjdf"));
}
}
See How do I compare strings in Java? and Reverse a string in Java might also be helpful (even though you probably did the above code as a programming exercise, it doesn't hurt to know that usually one would use already existing tools for this kind of thing).
The reason for using
"".equals(s)
instead of
s.equals("")
is as follows: In case s
is null
, the latter will throw a NullPointerException
(because you try to call a method on null
), whereas the former still works as you call a method on a "proper" string, see also Gracefully avoiding NullPointerException in Java However, I remember also some people criticizing this approach as this might make you miss the fact that s
is null
when it shouldn't be (in which case you should explicitly check handle that case).