Count Uppercase and Lowercase

Java coding interview problem for Character Problems: Count Uppercase and Lowercase.

Counting uppercase and lowercase characters is one of the most frequently asked Java String interview questions.

Although it appears simple, this problem helps interviewers evaluate your understanding of:

  • Character Classification
  • String Traversal
  • ASCII Values
  • Character Class
  • Loops
  • Conditional Statements
  • Time Complexity

Many advanced String interview problems build upon this concept, including:

  • Toggle Case
  • Convert to Uppercase
  • Convert to Lowercase
  • Password Validation
  • Character Frequency
  • Count Vowels and Consonants

Mastering this problem makes many String manipulation questions easier.


Problem Statement

Given a string,

count:

  • Number of uppercase letters
  • Number of lowercase letters

Ignore digits, spaces, and special characters.


Example 1

Input

CodeWithVenu

Output

Uppercase = 3

Lowercase = 9

Characters

C

W

V

are uppercase.


Example 2

Input

Java123

Output

Uppercase = 1

Lowercase = 3

Example 3

Input

HELLO world

Output

Uppercase = 5

Lowercase = 5

Example 4

Input

welcome@2026

Output

Uppercase = 0

Lowercase = 7

What is Character Classification?

Every character belongs to a category.

Examples

Uppercase

A

B

C

Lowercase

a

b

c

Digits

0

1

9

Special Characters

@

#

$

%

The goal is to identify whether a character is uppercase or lowercase.


Why is this Question Asked in Interviews?

Interviewers use this problem to evaluate:

  • Character Manipulation
  • String Traversal
  • Java Character API
  • ASCII Knowledge
  • Conditional Logic
  • Edge Case Handling

It is also a foundation for many text-processing algorithms.


Real-World Applications

Counting uppercase and lowercase letters is useful in many applications.


Password Validation

Check whether passwords contain uppercase and lowercase characters.

Example

Password123

Valid because it contains both uppercase and lowercase letters.


Text Editors

Display writing statistics.

Example

Uppercase Letters

Lowercase Letters

Data Validation

Ensure text follows required formatting rules.


Natural Language Processing (NLP)

Analyze writing styles and patterns.


Code Editors

Measure naming conventions like

camelCase

PascalCase

UPPER_CASE

Understanding Character Classification

Suppose we have

Java123

Read characters one by one.

J

Uppercase Count

1

Read

a

Lowercase Count

1

Read

v

Lowercase Count

2

Read

a

Lowercase Count

3

Read

1

Digit

Ignore.


Read

2

Ignore.


Read

3

Ignore.

Final

Uppercase = 1

Lowercase = 3

ASCII Table Explanation

Uppercase letters occupy

65

↓

90

ASCII

Lowercase letters occupy

97

↓

122

ASCII


Character ASCII
A 65
B 66
C 67
... ...
Z 90
a 97
b 98
c 99
... ...
z 122

Mathematical Concept

Uppercase

'A'

↓

65

Lowercase

'a'

↓

97

ASCII Difference

97 - 65

=

32

Uppercase Range

65

↓

90

Lowercase Range

97

↓

122

ASCII Visualization

Input

AbCde
A

↓

Uppercase
b

↓

Lowercase
C

↓

Uppercase
d

↓

Lowercase
e

↓

Lowercase

Final

Uppercase = 2

Lowercase = 3

Dry Run

Input

Java123
Character Type Uppercase Lowercase
J Uppercase 1 0
a Lowercase 1 1
v Lowercase 1 2
a Lowercase 1 3
1 Digit 1 3
2 Digit 1 3
3 Digit 1 3

Final

Uppercase = 1

Lowercase = 3

Approach 1 — Using Character Class (Recommended)

Java provides built-in methods inside the Character class.

Methods

Character.isUpperCase()
Character.isLowerCase()

These methods correctly support Unicode characters and are the most recommended interview solution.


Algorithm

  1. Initialize two counters.
  2. Traverse every character.
  3. If uppercase, increment uppercase count.
  4. Else if lowercase, increment lowercase count.
  5. Ignore remaining characters.

Java Program

public class CountUpperLowerCharacter {

    public static void countCharacters(String text) {

        int upper = 0;
        int lower = 0;

        for (char ch : text.toCharArray()) {

            if (Character.isUpperCase(ch)) {

                upper++;

            } else if (Character.isLowerCase(ch)) {

                lower++;

            }

        }

        System.out.println("Uppercase = " + upper);
        System.out.println("Lowercase = " + lower);

    }

    public static void main(String[] args) {

        countCharacters("CodeWithVenu");

    }

}

Output

Uppercase = 3

Lowercase = 9

Step-by-Step Code Explanation

Initialize counters.

int upper = 0;
int lower = 0;

Traverse string.

for(char ch : text.toCharArray())

Check uppercase.

Character.isUpperCase(ch)

Increment

upper++;

Check lowercase.

Character.isLowerCase(ch)

Increment

lower++;

Print results.

System.out.println(...)

Dry Run of Character Class Approach

Input

AbC12d
Character Action Uppercase Lowercase
A Uppercase 1 0
b Lowercase 1 1
C Uppercase 2 1
1 Ignore 2 1
2 Ignore 2 1
d Lowercase 2 2

Final

Uppercase = 2

Lowercase = 2

Advantages

  • Easy to understand.
  • Supports Unicode.
  • Most recommended interview solution.
  • Readable and maintainable.

Drawbacks

  • Slight method-call overhead.
  • Uses built-in APIs.

Approach 2 — Using ASCII Range Checks

Instead of using the Character class,

we can compare ASCII ranges directly.

Uppercase

A-Z

Lowercase

a-z

Algorithm

  1. Traverse the string.
  2. Check whether the character lies between 'A' and 'Z'.
  3. Increment uppercase count.
  4. Check whether it lies between 'a' and 'z'.
  5. Increment lowercase count.

Java Program

public class CountUpperLowerASCII {

    public static void countCharacters(String text) {

        int upper = 0;
        int lower = 0;

        for (char ch : text.toCharArray()) {

            if (ch >= 'A' && ch <= 'Z') {

                upper++;

            } else if (ch >= 'a' && ch <= 'z') {

                lower++;

            }

        }

        System.out.println("Uppercase = " + upper);
        System.out.println("Lowercase = " + lower);

    }

    public static void main(String[] args) {

        countCharacters("CodeWithVenu");

    }

}

Output

Uppercase = 3

Lowercase = 9

Step-by-Step Code Explanation

Check uppercase.

ch >= 'A' && ch <= 'Z'

Increment

upper++;

Check lowercase.

ch >= 'a' && ch <= 'z'

Increment

lower++;

Ignore digits and symbols.


Time & Space Complexity

Approach Time Extra Space
Character Class O(n) O(1)
ASCII Range Check O(n) O(1)

Where

  • n = Length of the string

Comparison of Approaches

Feature Character Class ASCII Range
Interview Friendly ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Performance ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Unicode Support ✅ ❌
Easy to Read ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐

Advantages

  • Both solutions execute in O(n) time.
  • Character Class supports Unicode and is suitable for international text.
  • ASCII Range Check is slightly faster for English alphabet input.
  • Both ignore digits, spaces, and symbols.

Drawbacks

  • Character Class has minor method-call overhead.
  • ASCII Range Check only works correctly for English letters.
  • Neither approach demonstrates functional programming techniques.

Approach 3 — Using Enhanced For Loop (Clean & Readable)

The Enhanced For Loop (for-each) provides one of the cleanest ways to iterate through characters in a string.

It is widely used in Java because of its readability and simplicity.


Why Enhanced For Loop?

Instead of writing

for (int i = 0; i < text.length(); i++) {
    char ch = text.charAt(i);
}

We can simply write

for (char ch : text.toCharArray()) {
}

This eliminates index management and improves readability.


Algorithm

  1. Initialize uppercase and lowercase counters.
  2. Convert string into a character array.
  3. Traverse using Enhanced For Loop.
  4. Count uppercase letters.
  5. Count lowercase letters.
  6. Print the result.

Java Program

public class CountUpperLowerEnhancedLoop {

    public static void countCharacters(String text) {

        int upper = 0;
        int lower = 0;

        for (char ch : text.toCharArray()) {

            if (Character.isUpperCase(ch)) {

                upper++;

            } else if (Character.isLowerCase(ch)) {

                lower++;

            }

        }

        System.out.println("Uppercase = " + upper);
        System.out.println("Lowercase = " + lower);

    }

    public static void main(String[] args) {

        countCharacters("Java Programming");

    }

}

Output

Uppercase = 2

Lowercase = 13

Advantages

  • Very readable.
  • Less code.
  • No index handling.
  • Recommended for interviews.

Drawbacks

  • Cannot directly access character index.
  • Still uses Character class methods.

Approach 4 — Using Java Streams

Java 8 Streams provide a concise functional programming approach.

Instead of manually looping,

we filter uppercase and lowercase characters separately.


Algorithm

  1. Convert string into IntStream.
  2. Filter uppercase characters.
  3. Count them.
  4. Filter lowercase characters.
  5. Count them.

Java Program

public class CountUpperLowerStreams {

    public static void countCharacters(String text) {

        long upper = text.chars()
                .filter(Character::isUpperCase)
                .count();

        long lower = text.chars()
                .filter(Character::isLowerCase)
                .count();

        System.out.println("Uppercase = " + upper);
        System.out.println("Lowercase = " + lower);

    }

    public static void main(String[] args) {

        countCharacters("CodeWithVenu");

    }

}

Output

Uppercase = 3

Lowercase = 9

Advantages

  • Modern Java.
  • Functional programming style.
  • Very concise.
  • Easy to combine with other Stream operations.

Drawbacks

  • Stream overhead.
  • Harder for beginners.
  • Less common in coding interviews.

Approach 5 — Using Regular Expressions (Regex)

Regular Expressions can identify uppercase and lowercase letters by removing everything else.

This is a concise approach for text analysis.


Algorithm

  1. Remove everything except uppercase letters.
  2. Count remaining characters.
  3. Remove everything except lowercase letters.
  4. Count remaining characters.

Java Program

public class CountUpperLowerRegex {

    public static void countCharacters(String text) {

        int upper = text.replaceAll("[^A-Z]", "").length();

        int lower = text.replaceAll("[^a-z]", "").length();

        System.out.println("Uppercase = " + upper);
        System.out.println("Lowercase = " + lower);

    }

    public static void main(String[] args) {

        countCharacters("CodeWithVenu123");

    }

}

Output

Uppercase = 3

Lowercase = 9

Advantages

  • Very compact.
  • Easy to understand.
  • Useful for text processing.

Drawbacks

  • Regex is slower than iteration.
  • Creates additional String objects.
  • Not recommended for performance-critical applications.

Unicode Considerations

Java uses UTF-16 encoding for String.

Examples

こんにちは
नमस्ते
ÄÖÜ

The Character class correctly handles Unicode character classification.

ASCII range checks (A-Z, a-z) and Regex patterns shown above only work correctly for English letters unless Unicode-aware patterns are used.


Edge Cases

Input Uppercase Lowercase
"" 0 0
"ABC" 3 0
"abc" 0 3
"12345" 0 0
"A1b@" 1 1
" " 0 0
null Handle appropriately

Time & Space Complexity

Approach Time Extra Space
Character Class O(n) O(1)
ASCII Range Check O(n) O(1)
Enhanced For Loop O(n) O(1)
Java Streams O(n) O(1)
Regex O(n) O(n)

Where:

  • n = Length of the string

Note: Although Regex scans the string in linear time, it creates intermediate strings, resulting in additional memory usage.


Comparison of All Approaches

Approach Interview Friendly Performance Unicode Support Readability Best Use Case
Character Class ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ✅ ⭐⭐⭐⭐⭐ Recommended interview solution
ASCII Range Check ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ❌ ⭐⭐⭐⭐ ASCII-only input
Enhanced For Loop ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ✅ ⭐⭐⭐⭐⭐ Production code
Java Streams ⭐⭐⭐⭐ ⭐⭐⭐ ✅ ⭐⭐⭐⭐ Modern Java
Regex ⭐⭐⭐ ⭐⭐ Limited* ⭐⭐⭐⭐ Quick text processing

*The regex examples use ASCII ranges. Unicode-aware regex patterns require different expressions.


Common Interview Mistakes

Mistake 1

Counting digits as letters.

Wrong

Java123

Digits should not increase either counter.


Mistake 2

Using ASCII checks for Unicode text.

Example

Ä

Ö

Ü

These are letters but fall outside the ASCII range.


Mistake 3

Ignoring empty strings.

Always verify

text.isEmpty()

or

text == null

before processing.


Mistake 4

Using String concatenation inside loops.

This problem only requires counting.

Avoid creating unnecessary String objects.


Mistake 5

Confusing uppercase and lowercase ASCII ranges.

Correct ranges

A-Z

65-90
a-z

97-122

Interview Follow-up Questions

Q1. Why is Character class preferred?

Q2. Why is ASCII range checking faster?

Q3. Why is Regex slower?

Q4. Which solution supports Unicode?

Q5. Can this be solved using Streams?

Q6. How would you count digits?

Q7. How would you count special characters?

Q8. What is the space complexity?

Q9. Can uppercase and lowercase be counted in one traversal?

Q10. How would you process a file containing millions of characters?


Related Problems

  • Toggle Case
  • Convert String to Uppercase
  • Convert String to Lowercase
  • Character Frequency
  • Count Vowels and Consonants
  • Remove Special Characters
  • Reverse a String
  • Most Frequent Character
  • First Non-Repeating Character

Key Takeaways

  • Counting uppercase and lowercase letters is a fundamental String manipulation problem.
  • Character Class is the safest and most recommended solution because it supports Unicode.
  • ASCII Range Check is slightly faster but limited to English letters.
  • Enhanced For Loop provides clean, readable production-quality code.
  • Java Streams offer a concise functional programming solution.
  • Regex is useful for quick text processing but is generally slower and creates additional objects.

Frequently Asked Interview Questions

Q1. Which solution is best for interviews?

The Character Class approach is the best choice because it is simple, readable, Unicode-aware, and widely accepted.


Q2. Which solution is fastest?

For ASCII-only input, ASCII Range Check is typically the fastest because it avoids method calls.


Q3. Why use Character.isUpperCase()?

It correctly identifies uppercase characters across many Unicode scripts, making it suitable for international applications.


Q4. Why is Regex slower?

Regex performs pattern matching and creates intermediate strings, increasing both CPU and memory usage compared to direct iteration.


Q5. Can uppercase and lowercase be counted in a single loop?

Yes.

The Character Class, ASCII Range Check, and Enhanced For Loop approaches count both values during a single traversal, giving an O(n) time complexity.


Interview Tip

If an interviewer asks:

"Count the number of uppercase and lowercase characters in a string."

Start with the Character Class solution because it is the standard Java approach.

Before coding, clarify:

  • Should digits and special characters be ignored?
  • Does the input contain only English letters or Unicode text?
  • How should null or empty strings be handled?

After presenting the Character Class solution, discuss alternative implementations:

  1. Character Class (recommended)
  2. ASCII Range Check (ASCII optimization)
  3. Enhanced For Loop (clean production code)
  4. Java Streams (functional programming)
  5. Regex (quick text-processing tasks)

This demonstrates strong Java fundamentals, familiarity with multiple approaches, and an understanding of their trade-offs.