Count UPPERCASE and lowercase Letter in Word or Sentense

How to count UPPER CASE letters and lowercase letters in given word or sentence?

// import java.lang.*;
import java.util.*;
public class Main {
  public static void main(String[] args) {
    Scanner scn = new Scanner(System.in);
    String str = scn.nextLine();
    int n = str.length();
    int upper = 0, lower = 0;
    for (int i =0 ; i < n ; i++)
    {
      char ch = str.charAt(i);
          if (ch>='A' && ch <= 'Z')
          {
            upper++;
          }
          else if (ch>='a' && ch <='z')
          {
            lower++;
          }
    }
               System.out.println("Upper count is: "+upper);
               System.out.println("Lower count is: "+lower);
  }
}

Code Explanation

  • import java.util.*: importing java.util package for Scanner class to get input from user.
  • public class main: This is an entry of program code.
  • public static void main: this is cosider as starting point to execute code.
  • Scanner scn: To get input from User.
  • int n = str.length();: Couting character length from User input.
  • int upper , lower: creating two variable to store count of upper case and lower case from word.
  • for loop: initializing for loop to count word letters so everytime it will check and letter format.
  • char: this is considering one char so everytime it hits and checking whether upper or lower case.
  • if (ch >= 'A' && ch <= 'Z'): upper case count 
  • else if (ch >= 'a' && ch <= 'z'): lower case count
  • System.out.println("Upper count is: " + upper): output printing for uppercase
  • System.out.println("Lower count is: " + lower): output printing for lowercase.


Similar Articles