Count number of characters in a string in Java

Before understanding our topic, we must first understand the meaning of a character.

A single alphabet or a single digit or a single symbol or a single space within a single quote is known as a character. It requires 2 bytes of memory because in java character is always represented in Unicode format.

Examples of character:  ‘1’, ‘@’, ‘b’, ‘ ‘, etc.

A single or collection of characters written in the double quote is called a string.

Examples of strings: “”, “123”, “a”, “5”, “@&”, etc.

Various predefined classes are present in java to create strings. Examples of predefined classes are String class, StringBuffer class, StringBuilder class, etc. But some of them make/create a fixed length string like String class whereas some of them have the ability to create a variable length string like StringBuffer and StringBuilder class.

Fixed length strings are immutable strings that means which cannot be modified on the same string object once created whereas variable length string can be modified hence called mutable strings.


The below method is not the only way to calculate the number of characters in a string. Here String class object is used to store the string in it.  Sometimes space is not considered as a character.

Steps to follow: Count the number of characters in a string in Java

  • Create a String class object to store the string in it.
  • Use the predefined method that is <String-object>.length() to calculate the length of the string.
  • Since the length of the string and the number of characters in a string are equal. We can calculate the total number of characters in a string in this way.
    public class Main
      public static void main(String[] args) {
        String st="CodeSpeedy is very good at providing content";   /*String class object is created named as st to store the string , other string class can also be used*/
        System.out.println(st.length()); /*we have directly print the solution but can also be stored in integer variable for any other purpose*/



    Thank you! Hope you enjoyed our content…

Leave a Reply

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