The String.endsWith() method tests whether a string concludes with a specified suffix, returning a boolean result (true or false).
Trailing Match Mechanics: Java evaluates suffixes by delegating directly to startsWith() using a calculated end offset. To inspect leading prefixes, see startsWith(). For substring presence anywhere, explore contains(). For backward delimiter searches, see lastIndexOf(), or slice text with substring().
The endsWith() method is defined in java.lang.String:
// Formal signature of String.endsWith() in java.lang.String
public boolean endsWith(String suffix)
| Parameter / Element | Type | Description & Operational Rule |
|---|---|---|
suffix |
String |
The character sequence to verify at the end of the string. |
| Return Value | boolean |
Returns true if the string ends with suffix; false otherwise. |
| Exception | Runtime | Throws NullPointerException if the argument suffix is null. |
Testing suffixes confirms whether a string concludes with specific character sequences:
String my_str = "plus2net";
System.out.println(my_str.endsWith("2net")); // true
System.out.println(my_str.endsWith("et")); // true
System.out.println(my_str.endsWith("t")); // true
System.out.println(my_str.endsWith("plus2net")); // true
System.out.println(my_str.endsWith("NET")); // false (case-sensitive)
System.out.println(my_str.endsWith("plus2")); // false
System.out.println(my_str.endsWith("pl")); // falseTerminal Output:
true
true
true
true
false
false
false
In Java's standard library implementation, endsWith() does not maintain duplicate scanning logic; it invokes startsWith() at an offset of length() - suffix.length():
String filename = "report.pdf";
String suffix = ".pdf";
// endsWith() delegates to startsWith() under the hood
boolean directCheck = filename.endsWith(suffix);
// Equivalent internal logic in java.lang.String:
int offset = filename.length() - suffix.length();
boolean delegated = filename.startsWith(suffix, offset);
System.out.println("endsWith result: " + directCheck); // true
System.out.println("startsWith offset: " + delegated); // trueTerminal Output:
endsWith result: true
startsWith offset: true
Choosing the right string inspection method depends on whether you require a boolean check or an index coordinate:
| Method | Return Type | Primary Purpose |
|---|---|---|
str.endsWith(suffix) |
boolean |
Validates trailing file extensions and domain endings. |
str.startsWith(prefix) |
boolean |
Validates leading protocols, roots, and command prefixes. |
str.lastIndexOf(target) |
int |
Returns numeric coordinate of the last occurrence for slicing. |
Because endsWith() is case-sensitive, file extensions like .JPEG and .jpeg must be normalized or compared using regionMatches():
String imageFile = "photo.JPEG";
String targetExt = ".jpeg";
// 1. Direct check: Case-sensitive (returns false)
System.out.println("Direct endsWith: " + imageFile.endsWith(targetExt)); // false
// 2. Approach A: toLowerCase() normalization
boolean approachA = imageFile.toLowerCase().endsWith(targetExt.toLowerCase());
System.out.println("toLowerCase: " + approachA); // true
// 3. Approach B: regionMatches() (Zero heap allocations!)
int offset = imageFile.length() - targetExt.length();
boolean approachB = (offset >= 0) && imageFile.regionMatches(true, offset, targetExt, 0, targetExt.length());
System.out.println("regionMatches: " + approachB); // trueTerminal Output:
Direct endsWith: false
toLowerCase: true
regionMatches: true
Passing null as the suffix argument raises a NullPointerException. Guard against crashes with null validation:
String document = "invoice.pdf";
String query = null;
// RISKY: Passing null throws NullPointerException
try {
System.out.println(document.endsWith(query));
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException on null suffix!");
}
// SAFE APPROACH: Guard against null before calling
boolean safe = (document != null && query != null) && document.endsWith(query);
System.out.println("Safe check result: " + safe);Terminal Output:
Caught NullPointerException on null suffix!
Safe check result: false
Validating uploaded file attachments against an array of approved media extensions:
public class FileFilterValidator {
private static final String[] ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"};
public static boolean isSupportedImage(String filename) {
if (filename == null) return false;
String lower = filename.toLowerCase();
for (String ext : ALLOWED_EXTENSIONS) {
if (lower.endsWith(ext)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println("header.PNG: " + isSupportedImage("header.PNG")); // true
System.out.println("doc.pdf: " + isSupportedImage("doc.pdf")); // false
}
}Terminal Output:
header.PNG: true
doc.pdf: false
Ensuring URL endpoints or directory paths conclude with a trailing forward slash:
public class PathFormatter {
public static String ensureTrailingSlash(String directoryPath) {
if (directoryPath == null || directoryPath.isEmpty()) return "/";
if (directoryPath.endsWith("/")) {
return directoryPath;
}
return directoryPath + "/";
}
public static void main(String[] args) {
System.out.println("Path 1: " + ensureTrailingSlash("/var/www/html")); // /var/www/html/
System.out.println("Path 2: " + ensureTrailingSlash("/var/www/html/")); // /var/www/html/
}
}Terminal Output:
Path 1: /var/www/html/
Path 2: /var/www/html/
Testing filename.endsWith("pdf") instead of .endsWith(".pdf") causes false positives on filenames like "not_a_pdf". Always include the leading period delimiter in extension checks.
Calling str.endsWith("") returns true for any non-null string. Be careful when validating user inputs against unvalidated suffix strings.
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringEndsWithFullDemo {
public static void main(String[] args) {
String url = "https: // www.plus2net.com";
// 1. Verify commercial TLD suffix
if (url.endsWith(".com")) {
System.out.println("Check 1 Passed: Domain ends with '.com'.");
}
// 2. Verify empty string behavior (always true)
if (url.endsWith("")) {
System.out.println("Check 2 Passed: Empty suffix returned true.");
}
// 3. Verify case-sensitivity
if (!url.endsWith(".COM")) {
System.out.println("Check 3 Passed: Uppercase '.COM' correctly evaluated to false.");
}
System.out.println("All String.endsWith() verification tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Domain ends with '.com'.
Check 2 Passed: Empty suffix returned true.
Check 3 Passed: Uppercase '.COM' correctly evaluated to false.
All String.endsWith() verification tests passed successfully!
No. endsWith() strictly requires a String parameter. Pass the character as a string (str.endsWith("t")) or check str.charAt(str.length() - 1) == 't'.
If suffix.length() > str.length(), endsWith() immediately returns false without throwing an exception.
Yes. endsWith() performs direct character-by-character boundary checks, avoiding regex compilation and state engine evaluation.
No. Calling str.endsWith(...) when str is null throws a NullPointerException.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.