Count the Length of a String in Java Without Using length()
Finding the length of a string without using the built-in length() method
is a popular beginner and interview question in Java.
This problem helps you understand:
- How strings are traversed internally
- Character-by-character processing
- Basic loop logic
How the Logic Works
To find the length of a string manually:
- Start a counter variable.
- Traverse the string character by character.
- Increment the counter for each character.
- Stop when all characters are processed.
Example 1
Input: "Java"
- J → count = 1
- a → count = 2
- v → count = 3
- a → count = 4
Length: 4
Example 2
Input: "Hello World"
- Includes space as a character
- Total characters counted = 11
Length: 11
Java Program to Count String Length Without length()
import java.util.Scanner;
public class StringLengthWithoutMethod {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
int count = 0;
for (char ch : str.toCharArray()) {
count++;
}
System.out.println("Length of the string: " + count);
}
}
Sample Output
Enter a string: Programming
Length of the string: 11
Important Notes
- Spaces are counted as characters.
- Special characters are also counted.
- This approach does not use
length().
Practice Challenges
- Count string length without converting it to a character array.
- Count length using a while loop instead of a for loop.
- Find the length of a string excluding spaces.
This program builds a strong foundation for understanding how strings work internally in Java.