Count the total number of characters in a string in Java

To count the total number of characters in a string in Java, you can use the length() method of the String class. The length() method returns the number of characters in the string.


Here's an example program that demonstrates how to count the total number of characters in a string:

import java.util.Scanner;

public class CountCharacters {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = scanner.nextLine();
        
        int count = str.length();
        
        System.out.println("Total number of characters: " + count);
    }
}


In this program, we first prompt the user to enter a string using the Scanner class. Then, we use the length() method of the String class to count the total number of characters in the string. Finally, we print the result to the console using System.out.println().