Reverse string using recursion in java

Java program for Reverse string using recursion. Here problem description and explanation.

// Reverse string using recursion in java
class ReverseString
{
	// This is reversing the string elements recursively
	public String reverseText(String text, int location)
	{
		// Base condition to stop the recursion process
		if (location >= 0)
		{
			// Recursive function call
			return text.charAt(location) + reverseText(text, location - 1);
		}
		// When no character remaining
		return "";
	}
	// This is handling the request process of reverse string elements
	public String reverse(String text)
	{
		// Display given string elements
		System.out.println("Before Text : [" + text + "]");
		return reverseText(text, text.length() - 1);
	}
	public static void main(String[] args)
	{
		ReverseString task = new ReverseString();
		String text = "ABCDE";
		text = task.reverse(text);
		// After reverse	
		System.out.println("After Text  : [" + text + "]\n");
		text = task.reverse("654A321");
		// After reverse	
		System.out.println("After Text  : [" + text + "]\n");
	}
}

Output

Before Text : [ABCDE]
After Text  : [EDCBA]

Before Text : [654A321]
After Text  : [123A456]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved