String Length Java

To find the String Length, the String class comes with length() method returning the number of characters as an int.
Following program on String Length illustrates.
public class Demo
  public static void main(String args[])
    String str1 = "hello";
    String str2 = "";

    int x = str1.length();
    System.out.println("hello length: " + str1.length());
    System.out.println("Empty string length: " + str2.length());

String Length
Output screenshot on String Length Java

An empty string is that one without any length (or without any characters). That is, double quotes if followed by double quotes. Empty string is a string but with length is zero.

Programming Trap: Do not confuse the length() method of String class with constant variable length of array. In array, we find the number of array elements with length (using length() with array is a compilation error).

One stop destination for all Java String and StringBuffer operations.

Leave a Comment

Your email address will not be published.