Java Program to Count Total Characters in a String

Write a Java program to count the total characters in a string with an example. We can use the built-in length function to get the length of a string. However, we use loops to get the total number of string characters.

In this Java example, we used for loop to iterate the string from start to end. Within that loop, we used the if statement to check whether the character is not empty. And if it is true, then the count value will increment from 0 to 1.

import java.util.Scanner;

public class CharactersInAString {
	private static Scanner sc;
	public static void main(String[] args) {
		String charsinstr;
		int count = 0;
		
		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter a String to Count Characters =  ");
		charsinstr = sc.nextLine();
		
		for(int i = 0; i < charsinstr.length(); i++)
		{
			if(charsinstr.charAt(i) != ' ') {
				count++;
			}
		}		
		System.out.println("\nThe Total Number of Characters  =  " + count);
	}
}
Java Program to Count Total Characters in a String using for loop

Java Program to Count Total Characters in a String using While loop

import java.util.Scanner;

public class CharactersInAString1 {
	private static Scanner sc;
	public static void main(String[] args) {
		String charsinstr;
		int count = 0, i = 0;
		
		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter a String to Count Characters =  ");
		charsinstr = sc.nextLine();
		
		while(i < charsinstr.length())
		{
			if(charsinstr.charAt(i) != ' ') {
				count++;
			}
			i++;
		}		
		System.out.println("\nThe Total Number of Characters  =  " + count);
	}
}
Please Enter a String to Count Characters =  hello world

The Total Number of Characters  =  10

Java Program to Count Total Characters in a String using functions

We separated the logic using functions in this Count Total number of String Characters example.

import java.util.Scanner;

public class CharactersInAString2 {
	private static Scanner sc;
	public static void main(String[] args) {
		String charsinstr;
		
		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter a String to Count Characters =  ");
		charsinstr = sc.nextLine();
		
		int count = TotalNumberofCharacters(charsinstr);
		
		System.out.println("\nThe Total Number of Characters  =  " + count);		
	}
	public static int TotalNumberofCharacters(String charsinstr) {
		int i, count = 0;
		
		for(i = 0; i < charsinstr.length(); i++)
		{
			if(charsinstr.charAt(i) != ' ') {
				count++;
			}
		}		
		return count;
	}	
}

Please Enter a String to Count Characters =  info tutorial

The Total Number of Characters  =  12