Java string length without using length() method.



To calculate the length of the string convert the string to a character array and count the number of elements in the array.

Example

Live Demo

public class StringLength {
   public static void main(String args[]) throws Exception {
      String str = "sampleString";
      int i = 0;
      for(char c: str.toCharArray()) {
         i++;
      }
      System.out.println("Length of the given string ::"+i);
   }
}

Output

Length of the given string ::12

Advertisements