1

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)

Here's my code:

    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);
    }
}
Michael Lihs
  • 5,664
  • 12
  • 40
  • 67
Zelda
  • 13
  • 4
  • `result.concat(null)` throws the NPE. So, does `reverseString(...)` ever return null? It does, if the string is empty. So you need to return something different. What's the reverse of an empty, non-null String? – yshavit Nov 02 '16 at 21:30
  • The `return null` in `reverseString()` seems a good candidate for introducing a `null` reference into your recursion. I don't see how it makes any sense in any case. – John Bollinger Nov 02 '16 at 21:30

2 Answers2

3

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 "";
Asaph
  • 147,774
  • 24
  • 184
  • 187
2

In addition to what @Asaph said you also need to assign this expression result.concat(reverseString(inString.substring(0, inString.length()-1)));

to your result variable so that it becomes:

result = result.concat(reverseString(inString.substring(0, inString.length()-1)));

Otherwise it won't work because the concat method of the String class does not return the same object from which it was called

alainlompo
  • 4,130
  • 3
  • 27
  • 39