Java Data Type How to - Get String length without using length() method








Question

We would like to know how to get String length without using length() method.

Answer

//from  ww  w.  j av  a  2 s.c o  m
public class Main {
  public static void main(String... args) {
    System.out.println("\nName Length is:" + len("java2s.com"));
  }

  public static int len(String ab) {
    char[] ac = ab.toCharArray();
    int i = 0, k = 0;

    for (i = 0, k = 0; ac[i] != '\0'; i++){
      k++;
    }
    return k;
  }
}