How to find length of string without using string function in java

In this post, we will see how to find the length of String without using any String function.
If String’s functions are allowed, there are two simple ways to find the length.

  • Use length function directly
  • Convert String to char array and find the lenght of char array

Let’s explore another way.


Using StringIndexOutOfBoundsException

You can take help of StringIndexOutOfBoundsException to find the length.

  • Use a for loop with variable i. Initialize i without specifying any condition
  • Call String’s charAt function on each index.As soon as i is higher than length of String, it will throw StringIndexOutOfBoundsException
  • We won’t do anything in catch block.
  • Return the value of i in the end.It will be length of the String.

Java program to find length of String:

Output

length of string : 23

That’s all about finding length of string without using string function in java.

Leave a Reply

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