Java – String Length

To find the length of a String in Java, call the length() method on the String. It returns an int representing the number of UTF-16 code units in the string. For ordinary text made of basic Latin letters, digits, spaces, and punctuation, this corresponds to the number of characters you usually expect to count.

The most common form is str.length(). The same length() method is also available on StringBuilder. This tutorial covers normal strings, empty and null values, spaces, string indexes, Unicode text, byte length, and the difference between String.length(), array length, and collection size().

Java String length() Syntax

length() takes no arguments and returns an integer.

</>
Copy
int length = str.length();

If str contains "Java", then str.length() returns 4.

Example 1 – String Length using String.length()

In this example, we shall initialize a string using String class. After that, we shall call length() method on the string and print the length to the console output.

StringLength.java

</>
Copy
/**
 * Java Example Program to find String Length
 */

public class StringLength {

	public static void main(String[] args) {
		//initialize a string
		String str = "tutorialkart";
		//get string length
		int len = str.length();
		System.out.print(len);
	}
}

Run the program from command prompt or run it from your IDE, like Eclipse, etc.

Output

12

The string "tutorialkart" contains 12 characters, so length() returns 12.

Java String Length Includes Spaces and Special Characters

Spaces, punctuation marks, tabs, and newline characters contribute to the length of a String. For example, the space between Hello and Java is counted.

</>
Copy
public class StringLengthWithSpaces {
    public static void main(String[] args) {
        String str = "Hello Java";

        System.out.println(str.length());
    }
}

Output

10

There are five letters in Hello, one space, and four letters in Java, giving a total length of 10.

Java String Length and String Indexes

String length is a count, so it does not “start at 0.” String indexes do start at 0. For a non-empty String of length n, valid indexes range from 0 through n - 1.

</>
Copy
String str = "Java";

System.out.println(str.length());
System.out.println(str.charAt(0));
System.out.println(str.charAt(str.length() - 1));

Output

4
J
a

For "Java", the length is 4 and the valid indexes are 0, 1, 2, and 3.

Example 2 – String Length using StringBuilder.length()

In this example, we shall initialize a StringBuilder, do some operations with the StringBuilder, and then find the length of the string in StringBuilder using length() method.

StringLength.java

</>
Copy
/**
 * Java Example Program to find String Length
 */

public class StringLength {
	public static void main(String[] args) {
		//you are building a string using string builder
		StringBuilder sb = new StringBuilder();
		//some operations on string builder
		sb.append("tutorialkart");
		sb.append(".com");
		//get string length
		int len = sb.length();
		System.out.print(len);
	}
}

The resulting StringBuilder contains "tutorialkart.com". It has 16 characters, so the output is 16.

Output

16

Example 3 – Length of Empty String

An empty String contains no characters. Calling length() on "" therefore returns 0.

StringLength.java

</>
Copy
/**
 * Java Example Program to find String Length
 */

public class StringLength {

	public static void main(String[] args) {
		//empty string
		String str = "";
		int len = str.length();
		System.out.println(len);
	}
}

The String is empty, so its length is zero.

Output

0

Example 4 – Length of Null String

A null reference is different from an empty String. An empty String is a real String object with length zero, while null means the variable does not refer to a String object. Calling length() through a null reference throws NullPointerException.

StringLength.java

</>
Copy
/**
 * Java Example Program to find String Length
 */

public class StringLength {

	public static void main(String[] args) {
		//null object in string
		String str = null;
		int len = str.length();
		System.out.println(len);
	}
}

Run the program and you shall see following exception thrown at runtime.

Output

Exception in thread "main" java.lang.NullPointerException
	at StringLength3.main(StringLength3.java:10)

Check for null Before Calling String.length()

If a String may be null, test the reference before calling length(). Do not automatically treat null as an empty String unless that behavior is appropriate for your application.

</>
Copy
String str = null;

if (str != null) {
    System.out.println(str.length());
} else {
    System.out.println("String is null");
}

String.length() vs Array length vs List.size() in Java

Java uses different forms to obtain the number of elements depending on the type. A String uses the length() method, an array uses the length field, and collections such as ArrayList commonly use the size() method.

Java typeHow to get the length or sizeExample
Stringlength()text.length()
Arraylengthnumbers.length
Listsize()items.size()

A common mistake is to write str.length for a String. Because length() is a method of String, the parentheses are required.

Java String length() and Unicode Characters

For Unicode text, String.length() technically returns the number of UTF-16 code units, not the number of Unicode code points a reader may perceive as characters. Many characters use one UTF-16 code unit, but supplementary Unicode characters use two.

</>
Copy
public class UnicodeStringLength {
    public static void main(String[] args) {
        String str = "A😊B";

        System.out.println(str.length());
        System.out.println(str.codePointCount(0, str.length()));
    }
}

Output

4
3

In this example, length() returns 4 UTF-16 code units, while codePointCount() reports 3 Unicode code points. User-perceived characters can be more complex still because some visible symbols are formed from multiple code points.

Java String Length Is Not the Same as String Size in Bytes

String.length() does not tell you how many bytes the text will use in a file or network message. Byte size depends on the chosen character encoding. To obtain the number of bytes after UTF-8 encoding, convert the String to a byte array and check the array’s length.

</>
Copy
import java.nio.charset.StandardCharsets;

String str = "Java";
int bytes = str.getBytes(StandardCharsets.UTF_8).length;

System.out.println(bytes);

Output

4

For ASCII characters such as those in "Java", the UTF-8 byte count happens to match the String length. That is not true for every Unicode character, so character length and encoded byte length should be treated as different measurements.

Count String Characters with a Loop in Java

For normal application code, use String.length(). If you are practicing loops and want to count the elements produced by a character array, you can increment a counter for each char. This is mainly a learning exercise and is not a replacement for length().

</>
Copy
String str = "Java";
int count = 0;

for (char ch : str.toCharArray()) {
    count++;
}

System.out.println(count);

Output

4

This loop counts Java char values. Like String.length(), it should not be interpreted as a general-purpose count of user-perceived Unicode characters.

Java String Length Summary

Use String.length() when you need the length of a Java String. An empty String has length zero, while calling length() on a null reference throws NullPointerException. Remember that String indexes start at zero even though the length itself is a count, and that String.length() measures UTF-16 code units rather than encoded bytes.

In this Java Tutorial, we learned how to find String length using String.length() and StringBuilder.length(), and how empty, null, Unicode, and byte-length cases differ.