Java string length without using length() method.

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Feb-2018 07:12:00
Advertisements