Java Program to Count Characters in a String

Java Programs

Problem: Write a Java program to count the number of characters in a given string.

The input string can also have white space which is definitely not a character, so we don’t need to count them.

Steps to count characters of a String in Java:

  1. Input a string (str).
  2. Run a loop from 0 to str.length().
    1. Read the character at position ‘i’ using str.charAt(i) as ch.
    2. Check if(ch!=’ ‘), If so then increment counter (c++).
  3. Print c.

Here is the Java program that implements the above steps:

import java.util.Scanner;
public class CountCharacters {
    public static void main(String args[]){
        Scanner in = new Scanner(;
        String str;     //To store string
        char ch;        //To store a single character
        int c=0;        //counter
        //input string
        System.out.println("Enter a String/Sentence");
        str = in.nextLine();     
        //Loop through each character
        for(int i=0; i<str.length(); i++){
            //Read character at 'i'
            ch = str.charAt(i);   
            //check if the character is not blank space,
            //if so then increment 'c'
            if(ch != ' ')
        //ouput counter
        System.out.println("Total characters: "+c);

Note: Use nextLine() instead of next() for sentence as the input.


Enter a String/Sentence
pencil programmer
Total characters: 16

Enter a String/Sentence
pencil programmer
Total characters: 16

Leave a Reply

Your email address will not be published. Required fields are marked *