Count the Length of a String in Java Without Using length() — Definition, Examples and Program

Learn how to find the length of a string in Java without using the built-in length() method. This blog explains the logic with examples, a Java program, and practice challenges.

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 the Logic Works

To find the length of a string manually:

  1. Start a counter variable.
  2. Traverse the string character by character.
  3. Increment the counter for each character.
  4. Stop when all characters are processed.

Example 1

Input: "Java"

Length: 4

Example 2

Input: "Hello World"

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

Practice Challenges

  1. Count string length without converting it to a character array.
  2. Count length using a while loop instead of a for loop.
  3. Find the length of a string excluding spaces.

This program builds a strong foundation for understanding how strings work internally in Java.