0
0
JavaHow-ToBeginner · 3 min read

How to Use startsWith and endsWith Methods in Java

In Java, use startsWith(String prefix) to check if a string begins with a specific prefix, and endsWith(String suffix) to check if it ends with a specific suffix. Both methods return a boolean value indicating true or false.
📐

Syntax

The startsWith and endsWith methods belong to the String class in Java. They check if a string starts or ends with a given substring.

  • boolean startsWith(String prefix): Returns true if the string starts with prefix.
  • boolean endsWith(String suffix): Returns true if the string ends with suffix.
java
String text = "Hello World";
boolean starts = text.startsWith("Hello");
boolean ends = text.endsWith("World");
💻

Example

This example shows how to use startsWith and endsWith to check parts of a string and print the results.

java
public class Main {
    public static void main(String[] args) {
        String message = "Welcome to Java programming!";

        boolean starts = message.startsWith("Welcome");
        boolean ends = message.endsWith("programming!");

        System.out.println("Starts with 'Welcome': " + starts);
        System.out.println("Ends with 'programming!': " + ends);

        // Checking with wrong case
        System.out.println("Starts with 'welcome': " + message.startsWith("welcome"));
    }
}
Output
Starts with 'Welcome': true Ends with 'programming!': true Starts with 'welcome': false
⚠️

Common Pitfalls

Common mistakes include:

  • Case sensitivity: startsWith and endsWith are case sensitive, so "Hello" is different from "hello".
  • Null strings: Calling these methods on a null string causes NullPointerException.
  • Empty strings: Checking with an empty string always returns true because every string starts and ends with an empty string.
java
public class PitfallExample {
    public static void main(String[] args) {
        String text = "Java";

        // Wrong: case sensitive check
        System.out.println(text.startsWith("java")); // false

        // Right: convert to lower case first
        System.out.println(text.toLowerCase().startsWith("java")); // true

        // Empty string check
        System.out.println(text.startsWith("") + " (always true)");

        // Null string example (uncomment to see error)
        // String nullStr = null;
        // System.out.println(nullStr.startsWith("J")); // Throws NullPointerException
    }
}
Output
false true true (always true)
📊

Quick Reference

MethodDescriptionReturns
startsWith(String prefix)Checks if string starts with prefixboolean (true/false)
endsWith(String suffix)Checks if string ends with suffixboolean (true/false)

Key Takeaways

Use startsWith() to check if a string begins with a specific substring.
Use endsWith() to check if a string ends with a specific substring.
Both methods are case sensitive and return boolean values.
Calling these methods on null strings causes errors.
Empty string as argument always returns true.