recursive reverse string java code example
Example 1: reverse array in java
int length = array.length;
for(int i=0;i<length/2;i++) {
int swap = array[i];
array[i] = array[length-i-1];
array[length-i-1] = swap;
}
or
Collections.reverse(Arrays.asList(array));
Example 2: reverse string using recursion java with explanation
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
Example 3: reverse string using recursion java with explanation
public class Test {
private static int i = 0;
public static void main(String args[]) {
reverse("Hello");
}
public static String reverse(String str) {
int localI = i++;
if ((null == str) || (str.length() <= 1)) {
return str;
}
System.out.println("Step " + localI + ": " + str.substring(1) + " / " + str.charAt(0));
String reversed = reverse(str.substring(1)) + str.charAt(0);
System.out.println("Step " + localI + " returns: " + reversed);
return reversed;
}
}