Count Uppercase and Lowercase Characters in a String in Java — Definition, Examples and Program

Learn how to count uppercase and lowercase characters in a string in Java using ASCII value comparison without using built-in string methods.

Count Uppercase and Lowercase Characters in a String in Java

Counting uppercase and lowercase characters in a string is a common string manipulation problem that helps understand ASCII values and character-level operations.

In this program, we identify characters based on their ASCII ranges instead of using built-in methods.

Understanding the Problem

Characters are classified as:

Example 1

Input: JavaProGRam

Output:

Example 2

Input: HELLOworld

Output:

Logic Explanation

  1. Traverse the string character by character.
  2. Check if character lies between 'A' and 'Z'.
  3. Check if character lies between 'a' and 'z'.
  4. Increment respective counters.

Java Program to Count Uppercase and Lowercase


import java.util.Scanner;

public class CountUpperLower {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = sc.nextLine();

        int upper = 0, lower = 0;

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);

            if (ch >= 'A' && ch <= 'Z') {
                upper++;
            } else if (ch >= 'a' && ch <= 'z') {
                lower++;
            }
        }

        System.out.println("Uppercase letters: " + upper);
        System.out.println("Lowercase letters: " + lower);
    }
}

Sample Output


Enter a string: JavaProGRam
Uppercase letters: 4
Lowercase letters: 7

Important Notes

Practice Challenges

  1. Also count digits and special characters.
  2. Convert uppercase to lowercase and vice versa.
  3. Ignore spaces while counting characters.

This program strengthens understanding of ASCII values and character-based string traversal in Java.