Monday, May 2, 2022

Question 8 : Find length of String without using any inbuilt method in java?

 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 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:

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.                            

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS