Suppose you are in the Java Interview and were asked to write a Java program determining the number of Uppercase letters or characters in a String. How could you answer this question or what could be your approach to solving this Java program? Well, one of the approaches we will discuss in this tutorial.
Steps
- Initial a variable int count = 0;
- Write enhanced for a loop – for(char c :str.toCharArray())
- Write an if condition to check whether the character is uppercase or not. If it is uppercase, then increment the count variable by 1.
- Finally, print the value of the count using System.out.println(count);
Java Program To Find the Number of Uppercase Letters in a String
package TestAutomationCentral; public class NumberOfUpperCaseLetters { public static void main(String[] args) { String str = "Test Automation Central"; int count = 0; for(char c :str.toCharArray()){ if(Character.isUpperCase(c)){ count++; } } System.out.println(count); }
Output:
3