Count Total Characters in a String in Java
Problem
The length of a string is the total number of characters it contains, including spaces and punctuation.
Given a string, count its total number of characters without using the built-in length() method.
Java Program
public class CountTotalCharacters {
public static void main(String[] args) {
String str = "Java Programming";
int count = 0;
// toCharArray() copies every character, including the space, into a new array
for (char c : str.toCharArray()) {
count++;
}
System.out.println("Total characters: " + count);
}
}Output
Core Logic
Converting the string to a char array and counting how many elements it has gets the length without ever calling length() directly.
- 1
str.toCharArray()converts the string into achar[]holding every character, including spaces. - 2A for-each loop visits each element of that array in turn.
- 3Each visit increments a running
countvariable by one. - 4After the loop finishes,
countequals the total number of characters.
"Java Programming", the loop runs once per character — letters and the one space — ending with count at 16.Key Point: This deliberately avoids length() to practice the underlying idea — in real code, str.length() is the correct and idiomatic way to get a string's length.
Why: toCharArray() copies every character into a new array before the loop counts them, so the temporary array itself holds all n characters.
Key Concepts
Approach 2: Using length()
public class CountTotalCharactersBuiltin {
public static void main(String[] args) {
String str = "Java Programming";
// length() reads the string's stored length directly — no scanning needed
System.out.println("Total characters: " + str.length());
}
}
Output
Core Logic
In real code, there's no reason to scan the string manually — length() already tracks the character count directly.
- 1Every
Stringstores its length internally, computed once when the string is created. - 2
str.length()simply reads that stored value and returns it. - 3No scanning, copying, or counting happens at call time.
"Java Programming".length() returns 16 immediately, without visiting a single character.Key Point: This is the version to actually use — the manual toCharArray() loop exists only to show what length() is conceptually doing under the hood.
Why: String stores its length as a field computed once at creation, so length() just reads that stored value instead of rescanning the characters.