Java Program to Count Total Characters in a String

Write a Java program to count 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 Java loops to get the total number of string characters.

In this java example, we used for loop to iterate string from start to end. Within that loop, we used 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 1

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

In this Java Count Total number of String Characters example, we separated the logic using functions.

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 =  java tutorial

The Total Number of Characters  =  12