Home Java Count Total Characters in a String in Java

Count Total Characters in a String in Java

In this example we show how to count the total amount of characters in a string using Java

Example

In this example we use a for loop to iterate through a string from start to end.

Within that loop, we use an if statement to check whether the character is not empty.

If it is not blankĀ  then the count value will increment

import java.util.Scanner;

public class JavaApplication1 
{
    private static Scanner myScanner;
    public static void main(String[] args) 
    {
        String charcount;
        int count = 0;

        myScanner= new Scanner(System.in);

        System.out.print("\nPlease Enter a String to Count =  ");
        charcount = myScanner.nextLine();

        for(int i = 0; i < charcount.length(); i++)
        {
            if(charcount.charAt(i) != ' ') 
            {
                count++;
            }
        }		
        System.out.println("\nThe Total Number of Characters  =  " + count);
    }
}

here is a test run

run:

Please Enter a String to Count = This is a test string

The Total Number of Characters = 17

You may also like