Java String endsWith() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The endsWith() method answers a focused question: “Does this string end with that suffix?” It returns true or false, which makes it ideal for file extensions, URL paths, and suffix-based validation.

01

Suffix Check

Match the ending.

02

Returns boolean

true or false.

03

String suffix

Parameter type.

04

Case Sensitive

A ≠ a by default.

05

vs startsWith()

End vs beginning.

06

File Extensions

.java, .txt, etc.

Definition and Usage

In Java, endsWith(String suffix) is defined on java.lang.String. It compares the trailing characters of the calling string with the suffix argument. If "Hello, World!" ends with "World!", the method returns true.

Unlike contains(), which searches anywhere in the text, endsWith() only cares about the final characters. Unlike startsWith(), it checks the suffix rather than the prefix.

💡
Beginner Tip

For file extensions, include the dot in the suffix: name.endsWith(".java"), not name.endsWith("java") unless you intentionally omit it.

📝 Syntax

The endsWith() method is declared in the String class:

java
public boolean endsWith(String suffix)

Parameters

  • suffix — the ending substring to test. Must not be null.

Return Value

Returns true if the string ends with suffix; otherwise false.

Exceptions

Throws NullPointerException if suffix is null.

⚡ Quick Reference

ExpressionResult
"Hello, World!".endsWith("World!")true
"Hello, World!".endsWith("Java")false
"Report.PDF".endsWith(".pdf")false (case-sensitive)
"notes.txt".endsWith("")true (empty suffix)
"abc".startsWith("ab")Prefix check, not suffix
Extension
file.endsWith(".java")

Java source file?

Negate
!url.endsWith("/")

Missing trailing slash

Ignore case
s.toLowerCase().endsWith(".pdf")

Normalize first

Anywhere?
text.contains("Java")

Use contains instead

Examples Gallery

These programs run in Java 8+. They show a matching suffix, a failed check, file extension validation, case-insensitive matching, and comparison with related methods.

📚 Getting Started

Check whether a greeting ends with "World!".

Example 1 — Basic Suffix Check

Test whether "Hello, World!" ends with "World!".

java
public class EndsWithExample {
    public static void main(String[] args) {
        String text = "Hello, World!";

        boolean endsWithWorld = text.endsWith("World!");

        System.out.println("Ends with 'World!'? " + endsWithWorld);
    }
}

How It Works

Java compares the last six characters W-o-r-l-d-! with the suffix. They match exactly, so the result is true.

Example 2 — Suffix Not Present

When the suffix does not match the ending, endsWith() returns false.

java
public class NotFoundDemo {
    public static void main(String[] args) {
        String text = "Hello, World!";

        System.out.println("Ends with 'Java'?  " + text.endsWith("Java"));
        System.out.println("Ends with 'Hello'? " + text.endsWith("Hello"));
    }
}

How It Works

"Java" is not at the end, and "Hello" appears at the start—not the suffix. Both checks return false.

📈 Practical Patterns

Real-world suffix checks and related methods.

Example 3 — File Extension Check

Filter filenames by extension—a classic endsWith() use case.

java
public class FileExtensionCheck {
    public static void main(String[] args) {
        String file1 = "Main.java";
        String file2 = "readme.txt";

        System.out.println(file1 + " is Java? " + file1.endsWith(".java"));
        System.out.println(file2 + " is Java? " + file2.endsWith(".java"));
    }
}

How It Works

Main.java ends with .java, so the first check passes. readme.txt ends with .txt instead.

Example 4 — Case-Insensitive Extension Check

Normalize both sides to lowercase when extension case may vary.

java
public class IgnoreCaseEndsWith {
    public static boolean endsWithIgnoreCase(String text, String suffix) {
        return text.toLowerCase().endsWith(suffix.toLowerCase());
    }

    public static void main(String[] args) {
        String report = "Annual-Report.PDF";

        System.out.println(endsWithIgnoreCase(report, ".pdf"));
    }
}

How It Works

Raw endsWith(".pdf") would fail on uppercase PDF. Lowercasing both strings first makes the comparison case-insensitive.

Example 5 — endsWith() vs startsWith() vs contains()

Each method checks a different part of the string.

java
public class SuffixVsPrefix {
    public static void main(String[] args) {
        String url = "https://codetofun.com/java";

        System.out.println("endsWith /java:    " + url.endsWith("/java"));
        System.out.println("startsWith https:  " + url.startsWith("https"));
        System.out.println("contains codetofun: " + url.contains("codetofun"));
    }
}

How It Works

All three return true here, but for different reasons: suffix at the end, prefix at the start, and substring anywhere. Choose the method that matches your rule.

🚀 Common Use Cases

  • File extension filters — accept only .java, .csv, or .json uploads.
  • URL and path rules — verify routes end with / or a version segment.
  • Input validation — ensure IDs or codes end with a required checksum digit.
  • Log parsing — branch logic when a line ends with an error marker.
  • Data cleanup — detect values that still end with unwanted whitespace characters before trimming.

🧠 How endsWith() Works

1

You pass a suffix

Java receives the host string and the ending substring to test.

Input
2

Null is rejected

A null suffix throws NullPointerException immediately.

Validate
3

Tail comparison

The JVM compares the last suffix.length() characters from back to front.

Compare
=

boolean answer

true if the ending matches; false if not.

📝 Notes

  • endsWith() is case-sensitive unless you normalize case first.
  • It checks only the suffix at the end—not the beginning or middle of the string.
  • endsWith("") always returns true for any string.
  • Include punctuation such as the dot in extensions: ".java" not "java" unless intended.
  • For prefix checks, use startsWith(); for anywhere-in-text checks, use contains().

⚡ Optimization

endsWith() is optimized for suffix matching and is the right default for extension and trailing-pattern checks. If you call the same check repeatedly in a hot loop, store the boolean result in a local variable. For very large strings in performance-critical code, avoid redundant case conversions—normalize once and reuse the lowered copy.

Conclusion

The endsWith() method is one of the clearest ways to test whether a string finishes with an expected suffix. Its boolean return type fits naturally inside conditionals for validation and filtering.

Remember case sensitivity, the empty-suffix edge case, and when to reach for startsWith() or contains() instead. With those details in mind, suffix checks become simple and readable in real programs.

💡 Best Practices

✅ Do

  • Use endsWith() for readable suffix and extension checks
  • Include the dot in file extensions when needed (".pdf")
  • Normalize case when users may type extensions in any capitalization
  • Guard against null suffix arguments before calling
  • Pair with startsWith() when both prefix and suffix matter

❌ Don’t

  • Assume endsWith() ignores case by default
  • Pass null as the suffix
  • Use contains() when you only care about the ending
  • Confuse suffix match with full string equality (equals())
  • Forget that endsWith("") is always true

Key Takeaways

Knowledge Unlocked

Five things to remember about endsWith()

Use these points whenever you validate string endings in Java.

5
Core concepts
02

Returns boolean

true or false.

Return
🔑 03

Case Sensitive

Normalize if needed.

Edge case
📁 04

Extensions

.java, .txt, .pdf.

Use case
🔢 05

vs startsWith()

End vs start.

Compare

❓ Frequently Asked Questions

endsWith(String suffix) checks whether the calling string ends with the exact suffix sequence. It returns true when the last characters match the suffix and false otherwise.
Call it on any String: filename.endsWith(".java"). The parameter must be a String. It returns a boolean.
Yes. "Report.PDF".endsWith(".pdf") returns false because uppercase and lowercase letters differ. Normalize with toLowerCase() on both sides when case should not matter.
endsWith() checks the suffix at the end. startsWith() checks the prefix at the beginning. contains() checks anywhere in the string. Pick the method that matches where you expect the text to appear.
Every string ends with the empty suffix, so endsWith("") always returns true. This is defined by the Java API and is useful to know for edge-case tests.
Use it to validate file extensions, route suffixes, formatted IDs, or any rule where the ending characters must match an expected pattern.

Validate String Endings with Confidence

Next up: compare string content the right way with equals() instead of ==.

Next: equals() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful