Java Examples
Java Examples
memu home questions

How to get the length of a String without using the string.length() method?

One way is to iterate through the each char in the string until you get a IndexOutOfBoundsException.

public class StringLength {
   public static void main(String[] args) {
      String str = "The cat in the hat";
      int length = 0;
      try {
         for (int i = 0;; i++) {
      } catch (IndexOutOfBoundsException e) {
          *  IndexOutOfBoundsException is caught when the index argument  
          *  is greater than the length of the string.
      System.out.println("str: " + str);
      System.out.println("length: " + length);


$ java StringLength
str: The cat in the hat
length: 18

Questions answered by this page:

String length without using length() method Get length of a String without using the Java Built In length method. Finding the length of the String without using inbuilt Java methods