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 :
[toc]
Using toCharArray is simplest solution.
Using toCharArray
Logic
- Convert string to char array using toCharArray method
- Iterate over char array and incrementing length variable.
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 without using length() method. Please refer below logic :Logic
- Initialize
iwith0and iterate over String without specifying any condition. So it will be always true. - Once value of
iwill be more than length of String, it will throwStringIndexOutOfBoundsExceptionexception. - We will
catchthe exception and return i after coming out ofcatchblock.
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.
That’s all about How to find length of string in java without using length() method.
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;
}
good logic