Quick Java code snippet to reverse a string using recursive method.

import java.util.Scanner;

public class StringRecursiveReverse {
	public String reverseString(String str) {
		String reverse = "";
		if (str.length() == 1) {
			return str;
		} else {
			reverse += str.charAt(str.length() - 1) + reverseString(str.substring(0, str.length() - 1));
			return reverse;
		}
	}

	public static void main(String args[]) {
		StringRecursiveReverse srr = new StringRecursiveReverse();
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a string to reverse");
		String original = scanner.nextLine();

		System.out.println("Result: " + srr.reverseString(original));
	}
}

Output
Reverse Java String using recursive method

-Advertisement-

Tagged in : Java

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.