How do I know the length of a string?

To get the length of a String object we can use the String.length() method. This method returns the string length as an int value. The length of the string is equals to the length of the sequence of characters represented by this string object, and it is equals to the number of 16-bit Unicode characters in the string.

The following code snippet shows how to use the length() method. We create a string object name and assign a text to it. Call the method and store the length returned to the length variable and print it out. We can also use the length() method to check if the string is empty by checking if the length is equals to zero.

package org.kodejava.lang;

public class StringLengthExample {
    public static void main(String[] args) {
        String name = "Kode Java - Learn Java by Examples";

        // Get the length of the string specified by the name
        // variable.
        int length = name.length();
        System.out.println("Length = " + length);

        // Set name to an empty string and test if it is empty.
        name = "";
        length = name.length();
        if (length == 0) {
            System.out.println("The string is empty!");
        }
    }
}

If you run this code you will get the following output:

Length = 34
The string is empty!
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.