Find length of String without using java inbuilt length method

Previous
Next
One of the interview question is “How will you find length of String without using inbuilt length method.”
There are many ways to find length of String.  Some of them are :
  • Using toCharArray
  • Using StringIndexOutOfBoundsException
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. 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.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

One Response

  1. Pras October 12, 2016

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog