How to Check If a String Is in Uppercase in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string is in uppercase in Java. We will explore different methods to achieve this, starting with comparing the original string to its uppercase version using toUpperCase().

Following that, you will learn how to iterate through a string and use the Character.isUpperCase() method to check the case of individual characters. Finally, we will address how to handle non-letter characters within the string when performing these checks.


Skills Graph

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

Compare String with toUpperCase()

In this step, we will learn how to compare strings in Java, specifically focusing on how to perform case-insensitive comparisons. This is a common task in programming, for example, when checking if a user entered "yes", "Yes", or "YES".

First, let's create a new Java file named StringCompare.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing StringCompare.java.

Now, open the StringCompare.java file in the editor and add the following code:

public class StringCompare {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "hello";

        // Case-sensitive comparison
        boolean areEqualCaseSensitive = str1.equals(str2);
        System.out.println("Case-sensitive comparison: " + areEqualCaseSensitive);

        // Case-insensitive comparison using toUpperCase()
        boolean areEqualCaseInsensitive = str1.toUpperCase().equals(str2.toUpperCase());
        System.out.println("Case-insensitive comparison using toUpperCase(): " + areEqualCaseInsensitive);
    }
}

Let's break down this code:

  • We declare two String variables, str1 and str2, with different casing.
  • str1.equals(str2) performs a case-sensitive comparison. It will return true only if the strings are exactly the same, including the case of the letters.
  • str1.toUpperCase() converts str1 to all uppercase letters ("HELLO").
  • str2.toUpperCase() converts str2 to all uppercase letters ("HELLO").
  • We then use .equals() to compare the uppercase versions of the strings, effectively performing a case-insensitive comparison.

Save the file by pressing Ctrl + S (or Cmd + S on Mac).

Now, let's compile and run this program in the Terminal. Make sure you are in the ~/project directory.

Compile the code:

javac StringCompare.java

If there are no errors, a StringCompare.class file will be created.

Now, run the compiled code:

java StringCompare

You should see the following output:

Case-sensitive comparison: false
Case-insensitive comparison using toUpperCase(): true

This output demonstrates that the case-sensitive comparison (equals()) returns false because "Hello" and "hello" are different due to casing, while the case-insensitive comparison using toUpperCase() returns true because both strings become "HELLO" when converted to uppercase.

Using toUpperCase() (or toLowerCase()) before comparing strings is a common way to perform case-insensitive comparisons in Java.

Use Character.isUpperCase() in Loop

In the previous step, we learned how to compare entire strings case-insensitively. Now, let's explore how to examine individual characters within a string and determine if they are uppercase. This is useful when you need to analyze the structure of a string, like counting uppercase letters or validating input format.

Java provides the Character class, which has helpful methods for working with individual characters. One such method is isUpperCase(), which checks if a given character is an uppercase letter.

Let's modify our StringCompare.java file to demonstrate this. Open ~/project/StringCompare.java in the editor and replace its content with the following code:

public class StringCompare {
    public static void main(String[] args) {
        String text = "Hello World";
        int uppercaseCount = 0;

        System.out.println("Analyzing the string: \"" + text + "\"");

        // 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 uppercase
            if (Character.isUpperCase(character)) {
                System.out.println("Found an uppercase character: " + character + " at index " + i);
                uppercaseCount++; // Increment the counter
            }
        }

        System.out.println("Total uppercase characters found: " + uppercaseCount);
    }
}

Let's understand the new parts of this code:

  • We declare a String variable text and an integer variable uppercaseCount initialized to 0.
  • We use a for loop to iterate through each character of the text 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 in the string.
  • Character.isUpperCase(character) checks if the character is an uppercase letter. This method returns true if the character is uppercase and false otherwise.
  • If isUpperCase() returns true, we print a message indicating the uppercase character and its index, and we increment uppercaseCount.

Save the file (Ctrl + S).

Now, compile and run the modified program in the Terminal from the ~/project directory:

Compile:

javac StringCompare.java

Run:

java StringCompare

You should see output similar to this:

Analyzing the string: "Hello World"
Found an uppercase character: H at index 0
Found an uppercase character: W at index 6
Total uppercase characters found: 2

This output shows that our program correctly identified the uppercase characters 'H' and 'W' in the string and counted them.

Using Character.isUpperCase() within a loop is a powerful technique for analyzing strings character by character. In the next step, we'll consider how to handle characters that are not letters.

Handle Non-Letter Characters

In the previous step, we used Character.isUpperCase() to identify uppercase letters. However, strings can contain more than just letters – they can include numbers, symbols, spaces, and punctuation. When analyzing strings, it's often necessary to distinguish between different types of characters.

The Character class provides other useful methods for this purpose, such as:

  • Character.isLetter(char ch): Checks if a character is a letter.
  • Character.isDigit(char ch): Checks if a character is a digit (0-9).
  • Character.isWhitespace(char ch): Checks if a character is a whitespace character (like space, tab, newline).

Let's modify our StringCompare.java file again to demonstrate how to handle non-letter characters and count different types of characters in a string. Open ~/project/StringCompare.java in the editor and replace its content with the following code:

public class StringCompare {
    public static void main(String[] args) {
        String text = "Hello World 123!";
        int letterCount = 0;
        int digitCount = 0;
        int whitespaceCount = 0;
        int otherCount = 0;

        System.out.println("Analyzing the string: \"" + text + "\"");

        // 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 the type of the character
            if (Character.isLetter(character)) {
                letterCount++;
            } else if (Character.isDigit(character)) {
                digitCount++;
            } else if (Character.isWhitespace(character)) {
                whitespaceCount++;
            } else {
                otherCount++; // Characters that are not letters, digits, or whitespace
            }
        }

        System.out.println("Total characters: " + text.length());
        System.out.println("Letter count: " + letterCount);
        System.out.println("Digit count: " + digitCount);
        System.out.println("Whitespace count: " + whitespaceCount);
        System.out.println("Other character count: " + otherCount);
    }
}

In this updated code:

  • We initialize counters for letters, digits, whitespace, and other characters.
  • Inside the loop, we use if-else if-else statements to check the type of each character using Character.isLetter(), Character.isDigit(), and Character.isWhitespace().
  • We increment the corresponding counter based on the character type.
  • Finally, we print the counts for each type of character.

Save the file (Ctrl + S).

Now, compile and run the program in the Terminal from the ~/project directory:

Compile:

javac StringCompare.java

Run:

java StringCompare

You should see output similar to this:

Analyzing the string: "Hello World 123!"
Total characters: 16
Letter count: 10
Digit count: 3
Whitespace count: 2
Other character count: 1

This output correctly identifies and counts the different types of characters in the string "Hello World 123!". The letters are 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' (10 total). The digits are '1', '2', '3' (3 total). The whitespace characters are the space between "Hello" and "World", and the space between "World" and "123" (2 total). The other character is '!' (1 total). The total count is 10 + 3 + 2 + 1 = 16, which matches the length of the string.

By using methods like Character.isLetter(), Character.isDigit(), and Character.isWhitespace(), you can write more robust code that can handle various types of characters within a string. This is crucial for tasks like data validation, parsing input, or analyzing text.

Summary

In this lab, we learned how to check if a string is in uppercase in Java. We explored two primary methods. First, we compared a string with its uppercase version using the toUpperCase() method and the equals() method to perform a case-insensitive comparison. This method is useful for checking if two strings are the same regardless of their casing.

Secondly, we learned how to iterate through a string and use the Character.isUpperCase() method within a loop to check if each character is an uppercase letter. We also considered how to handle non-letter characters during this process, ensuring our check is robust. These techniques provide different approaches for determining the uppercase status of a string based on the specific requirements of the task.