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.
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. |
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()); // 0Terminal Output:
str.length(): 8
welcome.length(): 11
empty.length(): 0
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
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
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
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
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...
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
Because strings are 0-indexed, calling str.charAt(str.length()) throws StringIndexOutOfBoundsException. The last character is always at str.charAt(str.length() - 1).
If a variable is null, calling str.length() throws a NullPointerException. Always guard checks with str != null && str.length() > 0.
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!
In Java, strings store their character array internally, so length() returns the count in O(1) constant time without iterating through the text.
Yes. Whitespace, tabs ( ), line feeds (
), and carriage returns () are all characters and each count towards length().
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.
Prefer str.isEmpty() for cleaner readability, although under the hood it simply evaluates return length() == 0;.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.