Solution: You can use try-catch block for catching StringIndexOutOfBoundException and when this exception is thrown, you can simply return I (Index at which you will get the exception)
Using toCharArray is the simplest solution.
Using toCharArray
Logic
- Convert string to char array using toCharArray method
- Iterate over char array and incrementing length variable.
Program:
public 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 the above program, you will get the 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
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:
publicclass 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 the above program, you will get the following output:: length of helloWorld string :19
That’s all about How to find the length of the string in java without using length() method.
Don't miss the next article!
Be the first to be notified when a new article or Kubernetes experiment is published.