Monday, April 24, 2023

5 ways to find length of String in Java - Example Tutorial

On another day, someone asked me, is there a way to find the length of String without using the length() method from java.lang.String class? I didn't ask why, because I know it might have been asked to him on Interviews. Before I explore ways to find the length of String, let's recap what does the length of String means in Java? Well, it's no different than C here, a number of characters in a String including whitespace, newlines are known as length of String. By knowing this, you can think of many approaches to calculating length e.g. getting a char array from String and counting a number of characters or many are by applying some clever tricks.

In this article, we are going to look at some unorthodox approaches of finding String length in Java, all of these don't use the built-in length() method but make use of Java API.

1. Using toCharArray() and array length property

2. Using lastIndexOf() method

3. Using Regular Expression

4. using StringBuilder

5. Using for loop

6. Using Reflection


If you run the above code in Java 1.7 update 40, you will get the following error, because the count field has been removed from java.lang.String class.

java.lang.NoSuchFieldException: count
        at java.lang.Class.getDeclaredField(Class.java:1938)
        at test.Test.main(Test.java:60)

The even length() method is using value array length property to find the length of String as shown below:

private final char value[];
public int length() {
   return value.length;
}


Java Program to Find the length of String without length() method of java.lang.String class

Here is our sample Java program to calculate the length of String without using the length() method of java.lang.String class of JDK.

5 Ways to Find length of String in Java without built-in length() method




And, here is the full Java program which you can copy and run in your IDE

package test;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Java Program to find length of String without using length() 
 * method of String class.
 *
 * @author Javin
 */
public class StringLengthFun {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String str = "Java is best Programming language \n";
        System.out.println("Length of String using length() method : " 
                                     + str.length());
       
        // Calculating length using toCharArray 
        // and .length property of array
        char[] rawChar = str.toCharArray();
        int length = rawChar.length;
        System.out.println("Length of String using toCharArray() 
                                    and array.length : " + length);
       
        // Using lastIndexOf method
        int lengthUsingLastIndexOf = str.lastIndexOf("");
        System.out.println("Length of String using lastIndexOf()  : "
                    + lengthUsingLastIndexOf);
       
        // Using Pattern and Matcher - not work with \\n
        Matcher m = Pattern.compile("$").matcher(str);
        m.find();
        int lenghtUsingRegEx = m.end();
        System.out.println("Length of String using Regular expression()  : " 
                                 + lenghtUsingRegEx);
       
        // Finding length of String using StringBuilder
        StringBuilder sb = new StringBuilder(str);
        int lengthUsingSB = sb.length();
        System.out.println("Length of String using StringBuilder : "
                         + lengthUsingSB);
       
       
        // Using toCharArray() and for loop
        int size = 0;
        for(char ch: str.toCharArray()){
            size++;
        }
        System.out.println("Length of String using for loop : " + size);
       
       
        // Using Reflection - Will not work in Java 1.7
        Field count;
        try {
             count = String.class.getDeclaredField("count");
             count.setAccessible(true);
             int lengthUsingReflection = count.getInt(str);
            
             System.out.println("Length of String using Reflection : "
                                   + lengthUsingReflection);
            
        } catch (NoSuchFieldException ex) {
            Logger.getLogger(Test.class.getName())
                  .log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (IllegalArgumentException ex){
            ex.printStackTrace();
        } catch (SecurityException ex) {
            Logger.getLogger(Test.class.getName())
                  .log(Level.SEVERE, null, ex);
        }     
    }
   
}
run:
Length of String using length() method : 35
Length of String using toCharArray() and array.length : 35
Length of String using lastIndexOf()  : 35
Length of String using Regular expression()  : 34
Length of String using StringBuilder : 35
Length of String using for loop : 35
Length of String using Reflection : 35


That's all about how to find the length of String in Java without using the built-in length() method. As we have seen there are many approaches, but remember this is just for fun, don't do this in production. Use length() to find out the length and use the isEmpty() method to check if String is empty or not.

No comments :

Post a Comment