Zelda Zelda - 1 month ago 7
Java Question

Returning the reverse of a string using recursion?

I'm trying to return the reverse of a string using recursion but I got a few errors. I'm new to recursion so I don't really know where to start. The errors I'm getting are:

Exception in thread "main" java.lang.NullPointerException

at java.lang.String.concat(String.java:2027)

at Recursion.reverseString(Recursion.java:30)

at Recursion.reverseString(Recursion.java:30)

at Recursion.reverseString(Recursion.java:30)

at Recursion.reverseString(Recursion.java:30)

at Recursion.reverseString(Recursion.java:30)

at Recursion.main(Recursion.java:46)

public static String reverseString (String inString)
{
String result = "";

if (inString.length() > 0) // if the string is empty
{
result = inString.charAt(inString.length()-1) + "";
result.concat(reverseString(inString.substring(0, inString.length()-1)));
return result;
}else{
return null;
}
}


// the testers

public static void main(String[] args){
String inString = "abcde";


// test the reverseString
String revString = reverseString(inString);
System.out.println(revString);

}
}

Answer

The exception stacktrace is telling you that null is being passed to the concat() method. The argument to concat() is your reverseString() method which returns null when the string is empty. Instead of returning null, you could return an empty String to avoid the NullPointerException. Replace the line:

return null;

with

return "";