Java ProgramsStringsCount Total Characters in a String

Count Total Characters in a String in Java

beginner·  Strings  ·  String

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.

Input
Java Programming
Output
Total characters: 16

Java Program

Java
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

Total characters: 16

Core Logic

Converting the string to a char array and counting how many elements it has gets the length without ever calling length() directly.

How It Works
  1. 1str.toCharArray() converts the string into a char[] holding every character, including spaces.
  2. 2A for-each loop visits each element of that array in turn.
  3. 3Each visit increments a running count variable by one.
  4. 4After the loop finishes, count equals the total number of characters.
For "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.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

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

toCharArray()for-each loopcounter variable

Approach 2: Using length()

Java
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

Total characters: 16

Core Logic

In real code, there's no reason to scan the string manually — length() already tracks the character count directly.

How It Works
  1. 1Every String stores its length internally, computed once when the string is created.
  2. 2str.length() simply reads that stored value and returns it.
  3. 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.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

Why: String stores its length as a field computed once at creation, so length() just reads that stored value instead of rescanning the characters.

Key Concepts

String.length()

Related Programs