Java String Length with Examples

Jan 26, 2020 · 2 mins read

To find length of a string in Java, you can can use the String.length() method. This method takes no parameters returns the length of the string as an int. The length is equal to the number of characters (or unicode code units) in the string.

String.length() Method Syntax

public int length()

Example

String domainName = "www.codeahoy.com"; // 16 characters
int length = domainName.length();
System.out.println("the length is: " + length);

Output

the length is: 16

Other Notes

  1. The length() method counts all characters (char values in a string) including whitespace characters e.g. new line, tabs, etc.
  2. The maximum length of a string is bounded by an int which is 2^31 - 1. In other words, a string can have a maximum of 2 billion characters.
  3. String.length() method is generally safe for bigger unicode characters. Let’s take a look at an example:
String fireEmoji = "\uD83D\uDD25"; // 🔥
int length = fireEmoji.length();
System.out.println("String.length() is: " + fireEmoji.length());
System.out.println("String.codePointCount() is: " + fireEmoji.codePointCount(0, fireEmoji.length()));

Output

String.length() is: 2
String.codePointCount() is: 1

In the example above, String.length() returns 2 because the emoji is represented as two char values (unpaired surrogates). But the String.codePointUnit returns 1 because it counts unpaired surrogates as 1 character. But for many use cases in practice, String.length() is sufficient.

Complete Example Code

public class StringLength {
    public static void main(String[] args) {
        String domainName = "www.codeahoy.com";
        int length = domainName.length();
        System.out.println("String.length() is: " + length);

        String fireEmoji = "\uD83D\uDD25"; // 🔥
        length = fireEmoji.length();
        System.out.println("String.length() of " + fireEmoji + " is: " + fireEmoji.length());
        System.out.println("String.codePointCount() of " + fireEmoji + " is: " + fireEmoji.codePointCount(0, fireEmoji.length()));
    }
}

Output

String.length() is: 16
String.length() of 🔥 is: 2
String.codePointCount() of 🔥 is: 1

You May Also Enjoy


If you like this post, please share using the buttons above. It will help CodeAhoy grow and add new content. Thank you!