w3resource

Java Recursive Method: Find the length of a string

Java Recursive: Exercise-10 with Solution

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:

Flowchart: Java  recursive Exercises: Find the length of a string.

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.



Follow us on Facebook and Twitter for latest update.