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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/recursive/java-recursive-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics