Java String length(): Measuring Character Count & Code Units

The String.length() method returns the number of 16-bit Unicode characters (UTF-16 code units) contained in the string.

Sizing Mechanics & Bounds: It runs in O(1) constant time. To access individual characters, see charAt(). For 32-bit Unicode emoji character counting, explore codePointCount(). For slicing text based on length coordinates, see substring(), or iterate with for loop.

1. Syntax & Method Signature 🔝

The length() method is defined directly in java.lang.String:

 // Formal signature of String.length() in java.lang.String
public int length()
Signature Element Type Operational Property
Parameters None Takes no arguments; operates directly on the target string.
Return Value int The total count of 16-bit UTF-16 code units in the string.
Time Complexity O(1) Constant time. The length is precomputed and stored internally.

2. Basic Length Examples 🔝

Calling length() counts every character, including spaces, numbers, and symbols:

String str = "plus2net";
System.out.println("str.length():         " + str.length());          // 8

String welcome = "Welcome to ";
System.out.println("welcome.length():     " + welcome.length());      // 11 (includes trailing space)

String empty = "";
System.out.println("empty.length():       " + empty.length());        // 0

Terminal Output:

str.length():         8
welcome.length():     11
empty.length():       0

3. Comparison: String length() vs. Array length vs. Collection size() 🔝

Java uses three distinct syntaxes to check element counts across different data structures:

Target Structure Syntax Form Type of Construct
String / CharSequence str.length() Instance method (requires parentheses).
Array (int[], String[]) array.length Public final field (no parentheses).
Collections (List, Set, Map) list.size() Interface method (requires parentheses).
 // 1. String length: METHOD call with parentheses ()
String text = "Java";
int strLen = text.length();

 // 2. Array length: public final FIELD without parentheses
int[] numbers = {10, 20, 30, 40};
int arrLen = numbers.length;

 // 3. Collection size: METHOD call on List / Set / Map
List<String> items = List.of("A", "B", "C");
int listSize = items.size();

System.out.println("String length: " + strLen + ", Array length: " + arrLen + ", List size: " + listSize);

Terminal Output:

String length: 4, Array length: 4, List size: 3

4. The Unicode Emoji Trap: Code Units vs. Code Points 🔝

Because Java strings store characters as 16-bit UTF-16 code units, emojis and rare international scripts span two code units (a surrogate pair), causing length() to return 2 for a single emoji:

 // Regular Latin word
String greeting = "Hello";
System.out.println("greeting.length():          " + greeting.length());  // 5

 // String containing an emoji (🚀 is a surrogate pair spanning 2 UTF-16 code units)
String rocket = "Rocket 🚀";
System.out.println("rocket.length():            " + rocket.length());    // 9 (Emoji counts as 2!)

 // True Unicode code point count
int trueCodePoints = rocket.codePointCount(0, rocket.length());
System.out.println("rocket.codePointCount:      " + trueCodePoints);     // 8 (True character count)

Terminal Output:

greeting.length():          5
rocket.length():            9
rocket.codePointCount:      8

5. Iterating Strings Using length() in Loops 🔝

In standard loops, length() defines the strictly upper bound < str.length(), guarding valid index positions 0 .. length - 1:

String word = "plus2net";

 // Standard loop using length() for bound checking
System.out.print("Characters: ");
for (int i = 0; i < word.length(); i++) {
    System.out.print(word.charAt(i) + " ");
}
System.out.println();

Terminal Output:

Characters: p l u s 2 n e t

6. Testing Emptiness: length() == 0 vs. isEmpty() vs. isBlank() 🔝

Modern Java offers specialized methods for testing string emptiness and whitespace content:

String s1 = "";
String s2 = "   ";
String s3 = "Java";

 // length() == 0 vs. isEmpty() vs. isBlank()
System.out.println("s1 length == 0: " + (s1.length() == 0) + ", isEmpty: " + s1.isEmpty() + ", isBlank: " + s1.isBlank());
System.out.println("s2 length == 0: " + (s2.length() == 0) + ", isEmpty: " + s2.isEmpty() + ", isBlank: " + s2.isBlank());
System.out.println("s3 length == 0: " + (s3.length() == 0) + ", isEmpty: " + s3.isEmpty() + ", isBlank: " + s3.isBlank());

Terminal Output:

s1 length == 0: true, isEmpty: true, isBlank: true
s2 length == 0: false, isEmpty: false, isBlank: true
s3 length == 0: false, isEmpty: false, isBlank: false

7. Production Recipe: Text Truncator with Ellipsis 🔝

Restricting lengthy article headlines or user previews to a maximum character threshold:

public class TextTruncator {
    public static String truncate(String text, int maxLength) {
        if (text == null || text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength - 3) + "...";
    }

    public static void main(String[] args) {
        String article = "Modern Java tutorial for high-performance enterprise applications.";
        System.out.println(truncate(article, 25));  // Modern Java tutorial...
    }
}

Terminal Output:

Modern Java tutorial...

8. Practical Recipe: Password Length Validator 🔝

Enforcing security length constraints on user registration inputs:

public class PasswordValidator {
    public static boolean isValidLength(String password) {
        if (password == null) return false;
        int len = password.length();
        return len >= 8 && len <= 32;
    }

    public static void main(String[] args) {
        System.out.println("pass1:     " + isValidLength("secret"));        // false (too short)
        System.out.println("pass2:     " + isValidLength("securePass123"));  // true (valid)
    }
}

Terminal Output:

pass1:     false
pass2:     true

9. Common Developer Pitfalls & Traps 🔝

The Off-By-One Index Equals Length Trap

Because strings are 0-indexed, calling str.charAt(str.length()) throws StringIndexOutOfBoundsException. The last character is always at str.charAt(str.length() - 1).

Invoking length() on a Null Reference

If a variable is null, calling str.length() throws a NullPointerException. Always guard checks with str != null && str.length() > 0.

10. Complete Compilable Java Program 🔝

You can compile and run this complete verification class locally in any Java IDE or environment:

public class StringLengthFullDemo {
    public static void main(String[] args) {
        String test = "plus2net";

         // 1. Verify character length
        if (test.length() == 8) {
            System.out.println("Check 1 Passed: Character count evaluated to 8.");
        }

         // 2. Verify empty string length is 0
        if ("".length() == 0) {
            System.out.println("Check 2 Passed: Empty string has length 0.");
        }

         // 3. Verify loop index bounds [0 .. length - 1]
        char first = test.charAt(0);
        char last = test.charAt(test.length() - 1);
        if (first == 'p' && last == 't') {
            System.out.println("Check 3 Passed: Boundary chars accessed safely.");
        }

        System.out.println("All String.length() verification checks passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: Character count evaluated to 8.
Check 2 Passed: Empty string has length 0.
Check 3 Passed: Boundary chars accessed safely.
All String.length() verification checks passed successfully!

11. Frequently Asked Questions (FAQ) 🔝

Is String.length() cached or recalculated every time?

In Java, strings store their character array internally, so length() returns the count in O(1) constant time without iterating through the text.

Does length() count spaces and newlines?

Yes. Whitespace, tabs ( ), line feeds ( ), and carriage returns () are all characters and each count towards length().

Why does an emoji have a length of 2?

Emojis reside outside the 16-bit Basic Multilingual Plane and require two UTF-16 surrogate code units. length() measures code units, so an emoji has length 2.

Should I use str.length() == 0 or str.isEmpty()?

Prefer str.isEmpty() for cleaner readability, although under the hood it simply evaluates return length() == 0;.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer