Joe Joe - 1 year ago 64
Java Question

calculate the number of characters in a string recursively

I am trying to calculate the number of characters in a string by using recursive method. here is my code in java

public class MainClass {

public int length(String str) {
if (str == null) {
return 0;
} else {
return length(str.substring(1))+1; // in eclipse it says : at MainClass.length(

public static void main(String args[]) {
MainClass m = new MainClass();

This line does not work :
return length(str.substring(1))+1;

How can I correct the code?

Answer Source

You forgot the case when your String argument is an empty string, include that in your check:

if (str == null || str.length()==0) {
  return 0;
} else {   

Please note that the Exception that you get contains valuable information about what's going wrong, in this case it's probably a StringIndexOutOfBoundsException because you call substring(1) on an empty String object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download