In recursion, a method call itself with modified data of the original call. This is done until some base case is reached, in which is no longer possible to modify the data.
In your case the base case is when the char array only consist of one element. This char will be the String. Otherwise it is the first element with the rest appended in a recursive call.
The String "Hello"
is 'H'
with toFormattedString({'e','l','l','o'})
appended. So if your char array contains only of one element (length==1)
just return this element as String value.
Otherwise take the first-element and go recursive to the remaining char array without the first element. Recursive until it is only one element left.
public static String toFormattedString(char[] a)
{
if (a.length==1) return String.valueOf(a[0]);
else
return a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length)) ;
}
You can even put the method body in one unreadable line(not recommended, I mentioned it just for fun):
return((a.length==1)?String.valueOf(a[0]):a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length)));
UPDATE: A switch
-statement gives readable code in this example:
public static String toFormattedString(char[] a)
{
switch (a.length)
{case 0 : return "";
case 1 : return String.valueOf(a[0]);
default: return a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length));
}
}
Usage:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(toFormattedString("Hello".toCharArray()));
}