Write a Java program to calculate length of a string using recursion


The calStringLength method takes a string as an input parameter and returns an integer value that represents the length of the string.

The method checks if the input string is an empty string, in which case it returns 0. If the string is not empty, the method recursively calls itself with the substring of the input string starting from the second character, and adds 1 to the result.

The base case for this recursion is when the input string becomes empty (i.e., when there are no more characters to process).

Source Code

import java.util.*;
public class StringLength
{
	public static void main(String[] args)
	{		
		String str ="Tutor Joe's";
		System.out.println("Given String : "+str);
		System.out.println("String Length : "+calStringLength(str));
	}
	private static int calStringLength(String str)
	{
		if (str.equals(""))
		{
			return 0;
		}
		else
		{
			return calStringLength(str.substring(1)) + 1;
		}
	}
}

Output

Given String : Tutor Joe's
String Length : 11