Java String endsWith(): Suffix Verification & File Type Validation

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().

1. Syntax & Method Signature 🔝

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.

2. Basic Suffix Checking Examples 🔝

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"));        // false

Terminal Output:

true
true
true
true
false
false
false

3. Under the Hood: Delegation to startsWith() 🔝

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);    // true

Terminal Output:

endsWith result:   true
startsWith offset: true

4. Comparison: endsWith() vs. startsWith() vs. lastIndexOf() 🔝

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.

5. Case-Insensitive Suffix Matching 🔝

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);                      // true

Terminal Output:

Direct endsWith: false
toLowerCase:     true
regionMatches:   true

6. Null-Safety & Defensive Coding 🔝

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

7. Production Recipe: File Extension Whitelist Validator 🔝

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

8. Practical Recipe: Trailing Slash Formatter 🔝

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/

9. Common Developer Pitfalls & Traps 🔝

The Missing Dot Extension Trap

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.

The Empty Suffix Always Returns True

Calling str.endsWith("") returns true for any non-null string. Be careful when validating user inputs against unvalidated suffix strings.

10. Complete Compilable Java Program 🔝

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!

11. Frequently Asked Questions (FAQ) 🔝

Can endsWith() accept a char primitive directly?

No. endsWith() strictly requires a String parameter. Pass the character as a string (str.endsWith("t")) or check str.charAt(str.length() - 1) == 't'.

What happens if the suffix is longer than the string?

If suffix.length() > str.length(), endsWith() immediately returns false without throwing an exception.

Is endsWith() faster than regular expressions?

Yes. endsWith() performs direct character-by-character boundary checks, avoiding regex compilation and state engine evaluation.

Does endsWith() work on null strings?

No. Calling str.endsWith(...) when str is null throws a NullPointerException.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer