Reverse String Recursively Java Example

Reverse String Recursively Java Example

This is to understand how method recursion works in Java and also very important interview question for Java Developer. Please have example below:

  • ReverseString.java:
package com.javahonk.javatoxml;

public class ReverseString {

	public static void main(String[] args) {
		String value = "JAVA HONK";

		System.out.println("Input value: "+value);
		System.out.println("Reverse simple way: "+getReverseString(value));
		System.out.println("Reverse recursively: "+reverseRecursively(value));
	}
	
	private static String getReverseString(String value){
		
		StringBuilder stringBuilder = new StringBuilder();
		
		char [] val = value.toCharArray(); 
		for (int i = val.length-1; i >= 0; i--) {
			char c = val[i];
			stringBuilder.append(c);
		}
		
		return stringBuilder.toString();
		
	}
	
	private static String reverseRecursively(String str) {
	    if ((null == str) || (str.length() <= 1)) {
	        return str;
	    }
	    return reverseRecursively(str.substring(1)) + str.charAt(0);
	}

}
  • Output:

Reverse String Recursively Java Example

  • If you are curious how recursion work then below is graph for above parameter:

Reverse String Recursively Java Example

  • For more information please refer Recursion in Oracle documentation

Leave a Reply

Your email address will not be published. Required fields are marked *