How to Check If a String Ends with a Specific Suffix in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string ends with a specific suffix in Java. This is a fundamental skill for tasks like validating file types or parsing data based on its ending. You will explore the endsWith() method, understand its case sensitivity, and learn how to combine it with startsWith() for more complex checks. Through hands-on examples, you will gain practical experience in using these string manipulation techniques in your Java programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/strings -.-> lab-559982{{"How to Check If a String Ends with a Specific Suffix in Java"}} java/string_methods -.-> lab-559982{{"How to Check If a String Ends with a Specific Suffix in Java"}} end

Use endsWith() to Verify Suffix

In this step, we will explore how to use the endsWith() method in Java to check if a string ends with a specific suffix. This is a common task when you need to validate file extensions, check for specific patterns, or process data based on its ending.

The endsWith() method is part of the String class in Java. It takes a single argument, which is the suffix you want to check for, and returns a boolean value: true if the string ends with the specified suffix, and false otherwise.

Let's create a simple Java program to demonstrate how endsWith() works.

  1. Open the HelloJava.java file in the WebIDE editor. If you don't have it open, you can find it in the File Explorer on the left, inside the project folder.

  2. Replace the existing code in HelloJava.java with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String fileName = "document.txt";
            boolean endsWithTxt = fileName.endsWith(".txt");
    
            System.out.println("Does '" + fileName + "' end with '.txt'? " + endsWithTxt);
    
            String imageUrl = "photo.jpg";
            boolean endsWithJpg = imageUrl.endsWith(".jpg");
    
            System.out.println("Does '" + imageUrl + "' end with '.jpg'? " + endsWithJpg);
    
            String documentName = "report.pdf";
            boolean endsWithDoc = documentName.endsWith(".doc");
    
            System.out.println("Does '" + documentName + "' end with '.doc'? " + endsWithDoc);
        }
    }

    In this code:

    • We declare three String variables: fileName, imageUrl, and documentName.
    • We use the endsWith() method on each string to check if it ends with a specific suffix (.txt, .jpg, .doc).
    • The results (true or false) are stored in boolean variables (endsWithTxt, endsWithJpg, endsWithDoc).
    • Finally, we print the results to the console using System.out.println().
  3. Save the HelloJava.java file (Ctrl+S or Cmd+S).

  4. Now, let's compile the program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Then, run the following command:

    javac HelloJava.java

    If there are no errors, the compilation will complete silently, and a HelloJava.class file will be created in the ~/project directory.

  5. Finally, run the compiled program using the java command:

    java HelloJava

    You should see output similar to this:

    Does 'document.txt' end with '.txt'? true
    Does 'photo.jpg' end with '.jpg'? true
    Does 'report.pdf' end with '.doc'? false

    This output shows the results of our endsWith() checks, confirming that document.txt ends with .txt, photo.jpg ends with .jpg, and report.pdf does not end with .doc.

You have successfully used the endsWith() method to check for string suffixes. This is a fundamental operation that you will use frequently in Java programming.

Test Suffix with Case Sensitivity

In the previous step, we learned how to use the endsWith() method. It's important to understand that the endsWith() method in Java performs a case-sensitive comparison. This means that "file.txt" ends with ".txt", but it does not end with ".TXT".

Let's modify our program to see this case sensitivity in action.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String fileName = "document.txt";
    
            // Case-sensitive check
            boolean endsWithLowercaseTxt = fileName.endsWith(".txt");
            System.out.println("Does '" + fileName + "' end with '.txt' (lowercase)? " + endsWithLowercaseTxt);
    
            // Case-sensitive check with uppercase suffix
            boolean endsWithUppercaseTxt = fileName.endsWith(".TXT");
            System.out.println("Does '" + fileName + "' end with '.TXT' (uppercase)? " + endsWithUppercaseTxt);
    
            String anotherFile = "IMAGE.JPG";
    
            // Case-sensitive check with lowercase suffix
            boolean endsWithLowercaseJpg = anotherFile.endsWith(".jpg");
            System.out.println("Does '" + anotherFile + "' end with '.jpg' (lowercase)? " + endsWithLowercaseJpg);
    
            // Case-sensitive check with uppercase suffix
            boolean endsWithUppercaseJpg = anotherFile.endsWith(".JPG");
            System.out.println("Does '" + anotherFile + "' end with '.JPG' (uppercase)? " + endsWithUppercaseJpg);
        }
    }

    In this updated code, we are explicitly testing endsWith() with both lowercase and uppercase suffixes to highlight the case-sensitive nature of the method.

  3. Save the HelloJava.java file.

  4. Compile the modified program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see output similar to this:

    Does 'document.txt' end with '.txt' (lowercase)? true
    Does 'document.txt' end with '.TXT' (uppercase)? false
    Does 'IMAGE.JPG' end with '.jpg' (lowercase)? false
    Does 'IMAGE.JPG' end with '.JPG' (uppercase)? true

    As you can see, the endsWith() method returned false when the case of the suffix did not exactly match the case in the string.

If you need to perform a case-insensitive check, you would typically convert both the string and the suffix to the same case (either lowercase or uppercase) before using endsWith(). We won't cover that in this specific step, but it's a useful technique to keep in mind.

Understanding case sensitivity is crucial when working with strings in Java, as many string methods are case-sensitive by default.

Combine startsWith() and endsWith() Checks

In addition to checking the end of a string with endsWith(), you can also check the beginning of a string using the startsWith() method. This method works similarly to endsWith(), taking a prefix as an argument and returning true if the string starts with that prefix, and false otherwise. Like endsWith(), startsWith() is also case-sensitive.

Combining startsWith() and endsWith() allows you to perform more specific checks on strings. For example, you might want to check if a filename starts with "temp_" and ends with ".log".

Let's update our program to use both startsWith() and endsWith().

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String logFileName = "temp_application_error.log";
    
            boolean startsWithTemp = logFileName.startsWith("temp_");
            boolean endsWithLog = logFileName.endsWith(".log");
    
            System.out.println("Does '" + logFileName + "' start with 'temp_'? " + startsWithTemp);
            System.out.println("Does '" + logFileName + "' end with '.log'? " + endsWithLog);
    
            // Combine checks using the logical AND operator (&&)
            boolean isTempLogFile = startsWithTemp && endsWithLog;
            System.out.println("Is '" + logFileName + "' a temporary log file? " + isTempLogFile);
    
            String anotherFile = "data_report.txt";
    
            boolean startsWithData = anotherFile.startsWith("data_");
            boolean endsWithTxt = anotherFile.endsWith(".txt");
    
            System.out.println("Does '" + anotherFile + "' start with 'data_'? " + startsWithData);
            System.out.println("Does '" + anotherFile + "' end with '.txt'? " + endsWithTxt);
    
            boolean isDataTxtFile = startsWithData && endsWithTxt;
            System.out.println("Is '" + anotherFile + "' a data text file? " + isDataTxtFile);
        }
    }

    In this code:

    • We introduce the startsWith() method to check the beginning of the strings.
    • We use the logical AND operator (&&) to combine the results of startsWith() and endsWith(). The && operator returns true only if both conditions are true.
  3. Save the HelloJava.java file.

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see output similar to this:

    Does 'temp_application_error.log' start with 'temp_'? true
    Does 'temp_application_error.log' end with '.log'? true
    Is 'temp_application_error.log' a temporary log file? true
    Does 'data_report.txt' start with 'data_'? true
    Does 'data_report.txt' end with '.txt'? true
    Is 'data_report.txt' a data text file? true

    This output demonstrates how you can use startsWith() and endsWith() together with logical operators to perform more complex string checks.

You have now learned how to use both startsWith() and endsWith() and combine them to verify both the beginning and end of a string. These methods are fundamental tools for string manipulation and validation in Java.

Summary

In this lab, we learned how to check if a string ends with a specific suffix in Java using the endsWith() method. We explored its basic usage to verify suffixes like file extensions and observed how it returns a boolean value indicating whether the string ends with the specified suffix.

We also investigated the case sensitivity of the endsWith() method and learned how to perform case-insensitive checks by converting the string and the suffix to the same case before comparison. Finally, we combined the startsWith() and endsWith() methods to check if a string both starts and ends with specific prefixes and suffixes, demonstrating how these methods can be used together for more complex string validation.