Find length of String without using java inbuilt length method

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:

class LenghtOfStringMain{
 
 public static void main(String args[]){
  
  String helloWorld="This is hello world";
  System.out.println("length of helloWorld string :"+getLengthOfStringWithCharArray(helloWorld));
  }

public static int getLengthOfStringWithCharArray(String str)
 {
  int length=0;
  char[] strCharArray=str.toCharArray();
  for(char c:strCharArray)
  {
   length++;
  }
  return length;
 }
When you run above program, you will get following output:
length of helloWorld string :19

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:

class LenghtOfStringMain{
 
 public static void main(String args[]){
  
  String helloWorld="This is hello world";
  System.out.println("length of helloWorld string :"+getLengthOfString(helloWorld));
  
  }
  
  public static int getLengthOfString(String str)
  {
    int i=0;
  try{
   for(i=0;;i++)
   {
    str.charAt(i);
   }
   
  }
  catch(Exception e)
  {
   
  }
  return i;
 }
When you run above program, you will get following output:
length of helloWorld string :19

Please go through java interview programs for more such programs and core java interview questions for more interview questions.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012