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
- Convert string to char array using toCharArray method
- Iterate over char array and incrementing length variable.
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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; } |
1 2 3 |
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
i
with0
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 throwStringIndexOutOfBoundsException
exception. - We will
catch
the exception and return i after coming out ofcatch
block.
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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; } |
1 2 3 |
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.
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