• Register
278 points
6 1

Here I’ll explain java program to count the letters, spaces, numbers and other characters of an input string.


import java.util.*;

public class CountAll 
  public static void main(String[] args) 
    Scanner myObj = new Scanner(System.in);
    String text;
    System.out.println("Enter String: "); 
    text= myObj.nextLine();   
		char[] ch = text.toCharArray();
		int letter = 0, space = 0, num = 0, other = 0;

		for(int i = 0; i < text.length(); i++)
			if(Character.isLetter(ch[i])) {
				letter ++ ;
			else if(Character.isDigit(ch[i])) {
				num ++ ;
			else if(Character.isSpaceChar(ch[i])) {
				space ++ ;
			else {
				other ++;
		System.out.println("Letters: " + letter);
		System.out.println("Space: " + space);
		System.out.println("Numbers: " + num);
		System.out.println("Other special characters: " + other);


Enter String: 
Kodlogs is a learning site which gives 100% efficiency to learn programming languages & solve your doubts...
Letters: 84
Space: 16
Numbers: 3
Other special characters: 5


In the above code, I created a Scanner Class to get the string entered by user.
  • The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
  • Character.isLetter() – Determines whether the specified char value is a letter.
  • Character.isDigit() – Determines whether the specified char value is a digit.
  • Character.isSpaceChar() – Determines if the specified character is a Unicode space character.
  • ch is a Primitive character type.



thanks for sharing this.
Interesting information&hellip; Awesome explanation of java program to count the letters, spaces, numbers and other characters of an input string. Keep it up, thank you.
Before reading this, I was in a terrible situation. I'm not sure how I missed this straightforward topic. Thank you very much.
Hey! Your article is full of knowledge and motivation for me. Thank u so much.