Java Programs 16: Java Program to Find Length of String Without Using Length Method

Hello Programmers,

An interview candidate was asked to write java code to find the length of given string WITHOUT USING LENGTH METHOD in Capgemini.

In this post, I will find length of string without using Length method but using some other method. :-p

There is another method in String class called lastIndexOf().

LastIndexOf() method:

As per Javadoc,

public int lastIndexOf(String str)

Returns the index within this string of the last occurrence of the specified substring. The last occurrence of the empty string “” is considered to occur at the index value this.length().

Highlighted in bold in above string is my solution actually. We will find last Index of an empty string (“”) which will give me length of actual string. Noter here, this method returns an index which starts from zero but here last occurrence of the empty string “” is considered to occur at the index value this.length().

Java Program:

Output:

If you like my posts, please like, comment, share and subscribe.

#HappyCoding

1 thought on “Java Programs 16: Java Program to Find Length of String Without Using Length Method

  1. Java Programs 16: Java Program to Find Length of String Without Using Length Method: Can be done using for loop:-
    public class StringLengthWithoutLengthFuc {
    public static void main(String[] args)
    {
    String str = “Rahul Singh”;
    int count = 0;
    for (char c : str.toCharArray())
    {
    count++;
    }
    System.out.println(“str ‘s length: ” + count);
    }

    }

Leave a Reply

Your email address will not be published. Required fields are marked *