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:
- Uppercase letters: A to Z (ASCII 65–90)
- Lowercase letters: a to z (ASCII 97–122)
Example 1
Input: JavaProGRam
Output:
- Uppercase letters: 4
- Lowercase letters: 7
Example 2
Input: HELLOworld
Output:
- Uppercase letters: 5
- Lowercase letters: 5
Logic Explanation
- Traverse the string character by character.
- Check if character lies between 'A' and 'Z'.
- Check if character lies between 'a' and 'z'.
- 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
- Digits and special characters are ignored.
- ASCII comparison avoids extra method calls.
- Works efficiently for large strings.
Practice Challenges
- Also count digits and special characters.
- Convert uppercase to lowercase and vice versa.
- Ignore spaces while counting characters.
This program strengthens understanding of ASCII values and character-based string traversal in Java.