How to find length of string in java without using length() method

One of the interview question is “How to find length of string in java without using length() method.”
There are many ways to find length of String.  Some of them are :
Using toCharArray is simplest solution.

Using toCharArray

Logic

Program

When you run above program, you will get following output:

Using StringIndexOutOfBoundsException

You must be wondering how we can use StringIndexOutOfBoundsException to find length of String without using length() method. Please refer below logic :

Logic

  • Initialize i with 0 and iterate over String without specifying any condition. So it will be always true.
  • Once value of i will be more than length of String, it will throw StringIndexOutOfBoundsException exception.
  • We will catch the exception and return i after coming out of catch block.

Program

When you run above program, you will get following output:

Please go through java interview programs for more such programs and core java interview questions for more interview questions.
That’s all about How to find length of string in java without using length() method.


import_contacts

You may also like:

Related Posts

Comments

  1. HI Arpit

    Your blog has been really good. We could achieve this also by recursion as follows.

    public int length(String s) {
    int l = 0;
    /* Equate to empty string */
    if (s.equals(“”)) {
    return 0;
    }

    int index = 0;
    l = length(s.substring(index+1)) + 1;
    return l;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.