How to Check If a String Starts with a Specific Prefix in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string starts with a specific prefix in Java using the startsWith() method. This hands-on exercise will guide you through applying the startsWith() method, testing its behavior with different cases, and understanding how it handles null and empty prefixes. By the end of this lab, you will be proficient in using this fundamental string manipulation technique.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/StringManipulationGroup -.-> java/strings("Strings") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/strings -.-> lab-559995{{"How to Check If a String Starts with a Specific Prefix in Java"}} java/exceptions -.-> lab-559995{{"How to Check If a String Starts with a Specific Prefix in Java"}} java/string_methods -.-> lab-559995{{"How to Check If a String Starts with a Specific Prefix in Java"}} end

Apply startsWith() to Check Prefix

In this step, you will learn how to use the startsWith() method in Java to check if a string begins with a specific prefix. This is a common operation when you need to process text based on how it starts.

The startsWith() method is part of the String class in Java. It takes a String argument, which is the prefix you want to check for. It returns true if the string starts with the specified prefix, and false otherwise.

Let's create a new Java file to practice using startsWith().

  1. Open the File Explorer on the left side of the WebIDE.

  2. Right-click in the ~/project directory and select "New File".

  3. Name the new file PrefixChecker.java.

  4. Open PrefixChecker.java in the editor and paste the following code:

    public class PrefixChecker {
        public static void main(String[] args) {
            String text = "Hello, Java!";
            String prefix = "Hello";
    
            boolean startsWithPrefix = text.startsWith(prefix);
    
            System.out.println("Does the text start with '" + prefix + "'? " + startsWithPrefix);
        }
    }

    In this code:

    • We declare a String variable text and initialize it with "Hello, Java!".
    • We declare another String variable prefix and initialize it with "Hello".
    • We call the startsWith() method on the text string, passing prefix as the argument. The result (true or false) is stored in the boolean variable startsWithPrefix.
    • Finally, we print the result to the console.
  5. Save the file (Ctrl+S or Cmd+S).

  6. Now, let's compile and run this program. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  7. Compile the Java file using the javac command:

    javac PrefixChecker.java

    If there are no errors, this command will create a PrefixChecker.class file in the ~/project directory.

  8. Run the compiled program using the java command:

    java PrefixChecker

    You should see the following output:

    Does the text start with 'Hello'? true

This output confirms that the string "Hello, Java!" indeed starts with the prefix "Hello".

Test Prefix with Different Cases

In the previous step, you successfully used startsWith() to check for a prefix. Now, let's explore how startsWith() handles different cases (uppercase and lowercase letters).

By default, the startsWith() method is case-sensitive. This means that "Hello" is considered different from "hello" or "HELLO". Let's modify our PrefixChecker.java file to see this in action.

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

  2. Modify the main method to include checks with different cases. Replace the existing main method with the following code:

    public class PrefixChecker {
        public static void main(String[] args) {
            String text = "Hello, Java!";
    
            String prefix1 = "Hello";
            String prefix2 = "hello";
            String prefix3 = "HELLO";
    
            boolean startsWithPrefix1 = text.startsWith(prefix1);
            boolean startsWithPrefix2 = text.startsWith(prefix2);
            boolean startsWithPrefix3 = text.startsWith(prefix3);
    
            System.out.println("Does the text start with '" + prefix1 + "'? " + startsWithPrefix1);
            System.out.println("Does the text start with '" + prefix2 + "'? " + startsWithPrefix2);
            System.out.println("Does the text start with '" + prefix3 + "'? " + startsWithPrefix3);
        }
    }

    In this updated code, we are checking if the text string starts with "Hello", "hello", and "HELLO".

  3. Save the file (Ctrl+S or Cmd+S).

  4. Open the Terminal and make sure you are in the ~/project directory.

  5. Compile the modified Java file:

    javac PrefixChecker.java
  6. Run the compiled program:

    java PrefixChecker

    You should see the following output:

    Does the text start with 'Hello'? true
    Does the text start with 'hello'? false
    Does the text start with 'HELLO'? false

This output clearly shows that startsWith() returned true only for the prefix "Hello" (matching the case of the original string) and false for "hello" and "HELLO". This demonstrates that startsWith() is case-sensitive.

If you need to perform a case-insensitive prefix check, you would typically convert both the original string and the prefix to the same case (either lowercase or uppercase) before using startsWith(). For example, you could use text.toLowerCase().startsWith(prefix.toLowerCase()). We won't implement that here, but it's a useful technique to keep in mind.

Check for Null and Empty Prefixes

In this step, we will investigate how the startsWith() method behaves when the prefix is null or an empty string (""). Understanding these edge cases is important for writing robust code.

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

  2. Modify the main method to test with a null prefix and an empty string prefix. Replace the existing main method with the following code:

    public class PrefixChecker {
        public static void main(String[] args) {
            String text = "Hello, Java!";
    
            String prefixNull = null;
            String prefixEmpty = "";
    
            // Check with a null prefix
            try {
                boolean startsWithPrefixNull = text.startsWith(prefixNull);
                System.out.println("Does the text start with null? " + startsWithPrefixNull);
            } catch (NullPointerException e) {
                System.out.println("Checking with null prefix resulted in: " + e);
            }
    
            // Check with an empty prefix
            boolean startsWithPrefixEmpty = text.startsWith(prefixEmpty);
            System.out.println("Does the text start with an empty string? " + startsWithPrefixEmpty);
        }
    }

    In this updated code:

    • We declare prefixNull and set it to null.
    • We declare prefixEmpty and set it to an empty string "".
    • We use a try-catch block when checking with prefixNull. This is because attempting to call a method on a null object in Java results in a NullPointerException. We catch this exception to see what happens.
    • We check with the empty string prefix prefixEmpty.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Open the Terminal and make sure you are in the ~/project directory.

  5. Compile the modified Java file:

    javac PrefixChecker.java
  6. Run the compiled program:

    java PrefixChecker

    You should see the following output:

    Checking with null prefix resulted in: java.lang.NullPointerException
    Does the text start with an empty string? true

This output demonstrates two important points:

  • Passing null as the prefix to startsWith() results in a NullPointerException. This is why it's crucial to handle potential null values before calling methods on them.
  • Passing an empty string ("") as the prefix to startsWith() returns true. This is because any string can be considered to start with an empty string.

Understanding how startsWith() handles null and empty strings is important for preventing errors and writing correct logic in your Java programs.

Summary

In this lab, you learned how to use the startsWith() method in Java to check if a string begins with a specific prefix. You practiced applying this method by creating a simple Java program, compiling it, and running it to see the output. This fundamental skill is essential for various string manipulation tasks in Java programming.