How to Check If a String Is in Lowercase in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string is in lowercase in Java. We will explore different methods to achieve this, starting with comparing strings while ignoring case using toLowerCase() and equalsIgnoreCase().

You will then learn how to iterate through a string and use Character.isLowerCase() to check each character individually. Finally, we will cover how to handle non-letter characters when performing this check.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/for_loop("For Loop") java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/for_loop -.-> lab-559986{{"How to Check If a String Is in Lowercase in Java"}} java/strings -.-> lab-559986{{"How to Check If a String Is in Lowercase in Java"}} java/string_methods -.-> lab-559986{{"How to Check If a String Is in Lowercase in Java"}} end

Compare String with toLowerCase()

In this step, we will learn how to compare strings in Java while ignoring the case of the letters. This is a common task when you want to check if two strings are the same regardless of whether they use uppercase or lowercase letters.

Let's create a new Java file to practice this.

  1. Open the WebIDE if it's not already open.

  2. In the File Explorer on the left, make sure you are in the ~/project directory.

  3. Right-click in the empty space in the File Explorer, select "New File", and name it CaseInsensitiveCompare.java.

  4. Open the CaseInsensitiveCompare.java file in the editor.

  5. Copy and paste the following code into the editor:

    public class CaseInsensitiveCompare {
        public static void main(String[] args) {
            String str1 = "Hello";
            String str2 = "hello";
            String str3 = "World";
    
            // Comparing strings directly (case-sensitive)
            boolean areEqualCaseSensitive = str1.equals(str2);
            System.out.println("Case-sensitive comparison of \"" + str1 + "\" and \"" + str2 + "\": " + areEqualCaseSensitive);
    
            // Comparing strings ignoring case
            boolean areEqualCaseInsensitive = str1.equalsIgnoreCase(str2);
            System.out.println("Case-insensitive comparison of \"" + str1 + "\" and \"" + str2 + "\": " + areEqualCaseInsensitive);
    
            // Comparing str1 and str3 ignoring case
            boolean areEqualStr1Str3 = str1.equalsIgnoreCase(str3);
            System.out.println("Case-insensitive comparison of \"" + str1 + "\" and \"" + str3 + "\": " + areEqualStr1Str3);
        }
    }

    In this code:

    • We declare three String variables: str1, str2, and str3.
    • str1.equals(str2) performs a case-sensitive comparison. It will return false because "Hello" and "hello" are different due to the uppercase 'H'.
    • str1.equalsIgnoreCase(str2) performs a case-insensitive comparison. It will return true because "Hello" and "hello" are the same when case is ignored.
    • We also compare str1 and str3 ignoring case to show that different words are still considered different.
  6. Save the file (Ctrl+S or Cmd+S).

  7. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  8. Compile the Java program using the javac command:

    javac CaseInsensitiveCompare.java

    If there are no errors, you will see no output. A CaseInsensitiveCompare.class file will be created in the ~/project directory.

  9. Run the compiled Java program using the java command:

    java CaseInsensitiveCompare

    You should see the following output:

    Case-sensitive comparison of "Hello" and "hello": false
    Case-insensitive comparison of "Hello" and "hello": true
    Case-insensitive comparison of "Hello" and "World": false

    This output confirms that equals() is case-sensitive, while equalsIgnoreCase() ignores case.

Using equalsIgnoreCase() is a convenient way to compare strings without worrying about whether letters are uppercase or lowercase.

Use Character.isLowerCase() in Loop

In the previous step, we learned how to compare entire strings while ignoring case. Sometimes, you might need to examine individual characters within a string and check if they are lowercase or uppercase. Java provides helpful methods for this in the Character class.

In this step, we will use the Character.isLowerCase() method within a loop to count the number of lowercase letters in a string.

  1. Open the WebIDE if it's not already open.

  2. In the File Explorer on the left, make sure you are in the ~/project directory.

  3. Create a new file named CountLowercase.java in the ~/project directory.

  4. Open the CountLowercase.java file in the editor.

  5. Copy and paste the following code into the editor:

    public class CountLowercase {
        public static void main(String[] args) {
            String text = "Hello World 123!";
            int lowercaseCount = 0;
    
            // Loop through each character in the string
            for (int i = 0; i < text.length(); i++) {
                char character = text.charAt(i); // Get the character at the current index
    
                // Check if the character is a lowercase letter
                if (Character.isLowerCase(character)) {
                    lowercaseCount++; // Increment the counter if it's lowercase
                }
            }
    
            System.out.println("The string is: \"" + text + "\"");
            System.out.println("Number of lowercase letters: " + lowercaseCount);
        }
    }

    Let's break down this code:

    • We have a String variable text containing a mix of uppercase letters, lowercase letters, numbers, and symbols.
    • We initialize an integer variable lowercaseCount to 0. This variable will store the count of lowercase letters.
    • We use a for loop to iterate through each character of the string. The loop runs from index 0 up to (but not including) the length of the string.
    • text.charAt(i) gets the character at the current index i.
    • Character.isLowerCase(character) is a method that returns true if the given character is a lowercase letter, and false otherwise.
    • If Character.isLowerCase() returns true, we increment lowercaseCount.
    • Finally, we print the original string and the total count of lowercase letters.
  6. Save the file (Ctrl+S or Cmd+S).

  7. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  8. Compile the Java program:

    javac CountLowercase.java

    If the compilation is successful, a CountLowercase.class file will be created.

  9. Run the compiled Java program:

    java CountLowercase

    You should see the following output:

    The string is: "Hello World 123!"
    Number of lowercase letters: 8

    The output shows that there are 8 lowercase letters in the string "Hello World 123!" ('e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd').

Using Character.isLowerCase() within a loop allows you to perform character-by-character analysis of a string, which is useful for various text processing tasks.

Ignore Non-Letter Characters

In the previous step, we counted lowercase letters. However, strings can contain various characters like numbers, spaces, and symbols. When comparing strings or analyzing their content, you often want to ignore these non-letter characters.

In this step, we will modify our program to process only letter characters and ignore everything else. We will use the Character.isLetter() method for this.

  1. Open the WebIDE if it's not already open.

  2. Open the CountLowercase.java file that you created in the previous step.

  3. Modify the code to include a check for whether a character is a letter before checking if it's lowercase. Replace the existing code with the following:

    public class CountLowercase {
        public static void main(String[] args) {
            String text = "Hello World 123!";
            int lowercaseCount = 0;
            StringBuilder lettersOnly = new StringBuilder(); // To store only letter characters
    
            // Loop through each character in the string
            for (int i = 0; i < text.length(); i++) {
                char character = text.charAt(i); // Get the character at the current index
    
                // Check if the character is a letter
                if (Character.isLetter(character)) {
                    lettersOnly.append(character); // Add the letter to our new string
    
                    // Check if the letter is lowercase
                    if (Character.isLowerCase(character)) {
                        lowercaseCount++; // Increment the counter if it's lowercase
                    }
                }
            }
    
            System.out.println("The original string is: \"" + text + "\"");
            System.out.println("Letters only string: \"" + lettersOnly.toString() + "\"");
            System.out.println("Number of lowercase letters (ignoring non-letters): " + lowercaseCount);
        }
    }

    Here's what we added and changed:

    • We introduced a StringBuilder called lettersOnly. StringBuilder is used for efficiently building strings, especially when you are adding characters in a loop.
    • Inside the loop, we added an if (Character.isLetter(character)) condition. This checks if the current character is a letter (either uppercase or lowercase).
    • If the character is a letter, we append it to the lettersOnly StringBuilder using lettersOnly.append(character).
    • The Character.isLowerCase(character) check is now nested inside the Character.isLetter() check, ensuring we only count lowercase letters among the characters that are actually letters.
    • Finally, we print the original string, the string containing only letters, and the count of lowercase letters among those letters.
  4. Save the file (Ctrl+S or Cmd+S).

  5. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  6. Compile the modified Java program:

    javac CountLowercase.java

    Ensure there are no compilation errors.

  7. Run the compiled Java program:

    java CountLowercase

    You should see the following output:

    The original string is: "Hello World 123!"
    Letters only string: "HelloWorld"
    Number of lowercase letters (ignoring non-letters): 8

    Notice that the "Letters only string" now contains only "HelloWorld", and the lowercase count is still 8, as we are only counting lowercase letters among the actual letters.

Using Character.isLetter() is very useful when you need to filter out non-alphabetic characters from a string before processing it further.

Summary

In this lab, we learned how to check if a string is in lowercase in Java. We explored two primary methods. First, we compared strings using equalsIgnoreCase() to perform case-insensitive comparisons, demonstrating how to check if two strings are the same regardless of letter case.

Second, although the full details were not provided, the steps indicate we would learn to iterate through a string using a loop and utilize Character.isLowerCase() to check if individual characters are lowercase, while also considering how to ignore non-letter characters during this process.