C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programs

Java program to count number of uppercase and lowercase letters in a string

In this Java program, we will learn how to count the number of uppercase and lowercase letters in a given string?
Submitted by Jyoti Singh, on October 02, 2017

Given a string and we have to count total number of uppercase and lowercase letters using Java program.

Example:

Input string: "AAAbbCCddEe"
Output:
Number of uppercase characters: 6
Number of lowercase characters: 5

In this code we have two inputs:

  1. An int input (no. of test cases or more clearly the number of strings user wants to check (say 5 i.e user wants to check 5 strings and the program will continue for 5 inputs).
  2. A string input (It will be a string entered by the user which needs to be checked).

For each string we will have two outputs

  1. The number of lowercase letters
  2. The number of uppercase letters

Consider the program: It will take number of inputs, string and print total number of uppercase and lowercase letters.

import java.util.Scanner;

public class CountUpperAndLowerCaseLetters
{
	public static void main(String[] args)
	{
		//Scanner is a class used to get the output from the user
		Scanner Kb=new Scanner(System.in);
		System.out.println("How man strings u want to check?");
		//Take the input of no. of test cases
		int t=Kb.nextInt();
		//looping until the test cases are zero
		while(t-->0){
			//Input the string
			System.out.println("Enter the string!");
			String s=Kb.next();
			//counter to count the uppercase and lowercase letters 
			int uppercase=0,lowercase=0;
			//looping until the string length is zero
			for(int i=0;i<s.length();i++){
				/*this function ---> isLowercase checks a particular character of the string by its index(charAt(index)) 
				that whether that character is a uppercase letter or lowercase letter,
				if it will be an uppercase letter then uppercase counter will be incremented and if 
				it is a lowercase character then lowercase counter will be incremented
				*/
				if(Character.isLowerCase(s.charAt(i))){
					lowercase++;
				}
				else if(Character.isUpperCase(s.charAt(i))){
					uppercase++;
				}
			}
			//Print the output 
			System.out.println("No. of lowercase letter : " + lowercase);
			System.out.println("No. of uppercase letter : " + uppercase);
			//to give a space of one line
			System.out.println();
		}
	}
}

Output

How man strings u want to check?
1
Enter the string!
AAAbbCCddEe
No of lowercase letter : 5
No of uppercase letter : 6






COMMENTS