How to find the length of a string in Java

Using the length() method

In the Java String class, the length() method is used to find the length of the given string. The length() method returns the total number of characters in the string.

The length() method is a public member method of the String Class, hence any variable of type string can access this method using the "."(dot) operator.

The syntax is

str.length()

Let us consider a string st = "Multinational company". The program below illustrates the use of the length() method to find the number of characters(including whitespace) in st.

public class strlen {
  public static void main(String args[]) {
    String st = "Multinational company"; //Initializing a String Object st
    int length = st.length(); //Calling the inbuilt length() method
    System.out.println("The length of the String \"" + st + "\" is: " + length);
  }
}

The output is

The length of the String "Multinational company" is: 21

Using the toCharArray() method

The toCharArray() method converts the string to a character array. By iterating through the array, a number of elements in the array are found and the length of the string is calculated.

Let us consider string str = "longestword". The example below illustrates the use of toCharArray() method to find the length of the str.

public class strlen {
  public static void main(String args[]) throws Exception {
    String str = "longestword";
    int i = 0;
    for (char c: str.toCharArray()) {
      i++;
    }
    System.out.println("Length of the given string: " + i);
  }
}

The output is

Length of the given string: 11
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions