Java Recursive Method: Find the length of a string
Recursive String Length
Write a Java recursive method to find the length of a given string.
Sample Solution:
Java Code:
public class StringLengthCalculator {
public static int calculateStringLength(String str) {
// Base case: if the string is empty, the length is 0
if (str.isEmpty()) {
return 0;
}
// Recursive case: remove the first character of the
// string and recursively call the method
// with the remaining substring, and add 1 to the length
return 1 + calculateStringLength(str.substring(1));
}
public static void main(String[] args) {
String input = "Java Exercises!";
int length = calculateStringLength(input);
System.out.println("The length of the string \"" + input + "\" is: " + length);
}
}
Sample Output:
The length of the string "Java Exercises!" is: 15
Explanation:
In the above exercises -
First, we define a class "StringLengthCalculator" that includes a recursive method calculateStringLength() to find the length of a given string str.
The calculateStringLength() method has two cases:
- Base case: If the string is empty (str.isEmpty()), we return 0 as the length of an empty string is 0.
- Recursive case: For any non-empty string, we remove the first character using str.substring(1) and recursively call the method with the remaining substring. We then add 1 to the length calculated from the recursive call. This process continues until the string is reduced to an empty string.
In the main() method, we demonstrate the calculateStringLength() method by finding the length of the string "Hello, World!" and printing the result.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Java program to recursively compute the length of a string without using the built-in length() method.
- Write a Java program to recursively calculate the length of a string while skipping whitespace characters.
- Write a Java program to compute the length of a string using tail recursion with an accumulator.
- Write a Java program to recursively determine the length of a string and then compare it with the length of its reversed version.
Java Code Editor:
Java Recursive Previous: Sum of odd numbers in an array.
Java Recursive Next: Generate all possible permutations.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics