Write a Java Program to copy one String to another using recursion


The program takes a string str1, copies its content to another string str2 using recursion, and then prints both strings. Here's a step-by-step explanation of how the program works:

  • The program initializes a character array str1 with the value "Java Exercises".
  • The program initializes a new character array str2 with the same length as str1.
  • The program calls the string_copy method with str1, str2, and an index of 0.
  • The string_copy method copies the character at the current index index from str1 to str2.
  • The string_copy method checks if the current index index is equal to the length of str1 minus 1. If it is, it means that all characters have been copied from str1 to str2, so the method returns.
  • Otherwise, the string_copy method calls itself with the same parameters but with the index increased by 1.
  • The program then prints the content of str1 and str2 using the String.valueOf() method.

Source Code

class CopyString
{
	public static void main(String[] args)
	{
		char str1[] = "Java Exercises".toCharArray();
		char str2[] = new char[str1.length];
		int index = 0;
		string_copy(str1, str2, index);
		System.out.println("String 1 : "+String.valueOf(str2));
		System.out.println("String 2 : "+String.valueOf(str1));
	}
	static void string_copy(char str1[],char str2[], int index)
	{
		str2[index] = str1[index];
		if (index == str1.length - 1)
		{
			return;
		}
		string_copy(str1, str2, index + 1);
	}
}

Output

String 1 : Java Exercises
String 2 : Java Exercises