Introduction
Counting characters in a string is one of the most fundamental operations in Java. Whether you're validating input length, processing text, or implementing string algorithms, understanding how to count characters efficiently is essential.
Java provides the length() method for strings, which returns the number of characters. While this seems straightforward, there are important distinctions about what counts as a "character" and how to handle special cases.
String.length() Method
The length() method returns the number of characters in a string.
public class StringLengthExample {
public static void main(String[] args) {
String str = "Hello World";
int length = str.length();
System.out.println("String: " + str);
System.out.println("Length: " + length);
}
}
Output
String: Hello World
Length: 11
Key Points
- Returns an
int. - Includes spaces in the count.
- Uses zero-based indexing (characters range from index
0tolength() - 1). - Does not modify the original string because
Stringis immutable.
Basic Examples
String s1 = "Java";
System.out.println(s1.length());
Output:
4
String s2 = "";
System.out.println(s2.length());
Output:
0
String s3 = "Hello World!";
System.out.println(s3.length());
Output:
12
String s4 = "123";
System.out.println(s4.length());
Output:
3
Character Counting Details
Spaces Are Counted
String withSpace = "Hello World";
System.out.println(withSpace.length());
Output:
11
Punctuation Is Counted
String withPunctuation = "Hello!";
System.out.println(withPunctuation.length());
Output:
6
Numbers Are Counted
String withNumbers = "Test123";
System.out.println(withNumbers.length());
Output:
7
Unicode Characters
String unicode = "café";
System.out.println(unicode.length());
Output:
4
Counting Specific Character Types
Sometimes you need to count only letters, digits, spaces, or special characters.
public class CharacterTypeCounter {
public static void countCharacterTypes(String input) {
int letters = 0;
int digits = 0;
int spaces = 0;
int others = 0;
for (char ch : input.toCharArray()) {
if (Character.isLetter(ch)) {
letters++;
} else if (Character.isDigit(ch)) {
digits++;
} else if (Character.isWhitespace(ch)) {
spaces++;
} else {
others++;
}
}
System.out.println("Letters: " + letters);
System.out.println("Digits: " + digits);
System.out.println("Spaces: " + spaces);
System.out.println("Other: " + others);
System.out.println("Total: " + input.length());
}
public static void main(String[] args) {
countCharacterTypes("Hello World 123!");
}
}
Output
Letters: 10
Digits: 3
Spaces: 2
Other: 1
Total: 16
Counting Specific Characters
Count Vowels
String text = "Hello World";
int vowelCount = 0;
for (char ch : text.toCharArray()) {
if ("aeiouAEIOU".indexOf(ch) >= 0) {
vowelCount++;
}
}
System.out.println("Vowels: " + vowelCount);
Output
Vowels: 3
Count a Specific Character
String target = "Hello";
int count = 0;
for (char ch : target.toCharArray()) {
if (ch == 'l') {
count++;
}
}
System.out.println("Count of 'l': " + count);
Output
Count of 'l': 2
Using replace()
String input = "Mississippi";
int frequency =
input.length() -
input.replace("s", "").length();
System.out.println("Frequency of 's': " + frequency);
Output
Frequency of 's': 4
Character vs String Length
There is an important difference between a char and a String.
char c = 'A';
// c.length(); // Not valid
String s = "A";
System.out.println(s.length());
System.out.println(Character.charCount(c));
Output
1
1
A char is a primitive type and does not have a length() method, whereas a String provides the length() method.
Performance Considerations
Time Complexity
| Operation | Time Complexity |
|---|---|
String.length() |
O(1) |
Java stores the string length internally, so calling length() is a constant-time operation.
Efficient Character Counting
Method 1: Loop
int countA = 0;
for (char ch : input.toCharArray()) {
if (ch == 'a') {
countA++;
}
}
Time Complexity: O(n)
Method 2: Using replace()
int count =
input.length() -
input.replace("a", "").length();
Time Complexity: O(n)
Method 3: Using Streams
long count =
input.chars()
.filter(c -> c == 'a')
.count();
Time Complexity: O(n)
Although all three methods are linear, a simple loop is generally the fastest because it avoids additional object creation.
Real-World Applications
Application 1: Input Validation
public class InputValidator {
public static boolean isValidPassword(String password) {
if (password == null) {
return false;
}
int length = password.length();
return length >= 8 && length <= 20;
}
public static void main(String[] args) {
System.out.println(isValidPassword("pass123"));
System.out.println(isValidPassword("secure123"));
}
}
Output
false
true
Application 2: String Truncation
public class StringTruncator {
public static String truncate(String input,
int maxLength) {
if (input == null) {
return "";
}
if (input.length() <= maxLength) {
return input;
}
return input.substring(0, maxLength) + "...";
}
public static void main(String[] args) {
String text = "This is a long text";
System.out.println(truncate(text, 10));
}
}
Output
This is a ...
Application 3: Message Formatting
public class MessageFormatter {
public static String formatWithMaxLength(
String message,
int maxLength) {
if (message.length() <= maxLength) {
return message;
}
return message.substring(0, maxLength - 3) + "...";
}
public static void main(String[] args) {
String msg = "Welcome to Java Programming";
System.out.println(
formatWithMaxLength(msg, 15));
}
}
Common Mistakes
Mistake 1: Using .length Instead of .length()
❌ Wrong
String str = "hello";
// int len = str.length;
✅ Right
String str = "hello";
int len = str.length();
For arrays:
int[] arr = {1, 2, 3};
int arrLength = arr.length;
Arrays use the length property, while String uses the length() method.
Mistake 2: Assuming length() Counts Unicode Characters Perfectly
String emoji = "Hello 😊";
System.out.println(emoji.length());
Output:
8
Some Unicode characters, such as emojis, occupy two UTF-16 code units, so length() counts code units rather than user-perceived characters.
Mistake 3: Not Handling Null Strings
❌ Wrong
String input = null;
System.out.println(input.length());
This throws a NullPointerException.
✅ Right
if (input != null && input.length() > 0) {
// Safe to use
}
Frequently Asked Questions
Q1: Is length() O(1) or O(n)?
Answer: length() is O(1) because Java stores the string length internally.
Q2: Can I count characters without using length()?
Answer: Yes.
input.toCharArray().length
Q3: Does length() include null characters?
Answer: Java strings do not contain C-style null terminators (\0). Strings are stored using UTF-16.
Q4: What is the maximum string length?
Answer: The theoretical limit is Integer.MAX_VALUE (2³¹ − 1), although available heap memory is usually the limiting factor.
Q5: Does length() count bytes or characters?
Answer: It counts UTF-16 code units, not bytes.
Q6: How do I count only alphanumeric characters?
Use:
Character.isLetterOrDigit(ch)
Q7: Can I get the length of a StringBuilder?
Yes.
StringBuilder builder = new StringBuilder("Java");
System.out.println(builder.length());
Q8: Is there a difference between length and size()?
- Arrays use the
lengthproperty. - Strings use the
length()method. - Collections use the
size()method.
Q9: How do I find the longest string in a list?
String longest =
list.stream()
.max((s1, s2) ->
Integer.compare(
s1.length(),
s2.length()))
.orElse("");
Q10: Does whitespace count in length()?
Answer: Yes. Every character, including spaces, tabs, and other whitespace characters, contributes to the total length.