DEV Community

Cover image for Java endsWith() Method: A Beginner's Guide with Real-World Examples
Satyam Gupta
Satyam Gupta

Posted on

Java endsWith() Method: A Beginner's Guide with Real-World Examples

Java endsWith() Method: Your Go-To Tool for Checking Strings

Ever found yourself scrolling through lines of code, trying to figure out if a filename is a .jpg or a .pdf? Or maybe you're validating user input, making sure an email address actually ends with ".com" or ".org"?

If you've been nodding your head, you're in the right place. Manually checking the end of a string can be a real pain—like trying to find the end of a roll of tape in the dark. But what if I told you Java has a built-in, super-simple method that does all the heavy lifting for you?

Let's talk about the Java String endsWith() method. It's one of those "small but mighty" tools that, once you master it, you'll wonder how you ever coded without it.

In this deep dive, we're not just going to skim the surface. We'll break down what it is, how it works, and then jump into some real-world scenarios where it absolutely saves the day. Ready to level up your Java game? Let's get into it.

What Exactly is the Java endsWith() Method?
In the simplest terms, endsWith() is a method that belongs to the String class in Java. Its only job is to answer a simple yes-or-no question: "Does this string end with the characters I'm specifying?"

It's like a digital bouncer for your strings, checking the guest list (the ending characters) and only letting the right ones through.

Here's the formal signature straight from the Java docs:
public boolean endsWith(String suffix)

Let's translate that from "programmer-ese" to plain English:

public: It's accessible from anywhere in your program.

boolean: This is the most important part. It means the method will only ever return one of two things: true (yes, it does end with that suffix) or false (nope, it doesn't).

endsWith: The name of the method itself.

String suffix: This is the parameter—the piece of text you want to check for at the end of your original string.

The key thing to remember is that this method is case-sensitive. "Hello" and "hello" are two completely different worlds to the endsWith() method.

How to Use endsWith(): The Basics with Code Examples
Enough theory; let's see this bad boy in action. The syntax is so straightforward you'll probably memorize it after the first example.

Example 1: The Absolute Basics
java
public class EndsWithExample {
public static void main(String[] args) {
String fileName = "document.pdf";

    // Check if the file name ends with ".pdf"
    boolean result = fileName.endsWith(".pdf");

    System.out.println("Does the file end with '.pdf'? " + result);
}
Enter fullscreen mode Exit fullscreen mode

}
Output:
Does the file end with '.pdf'? true

Boom. It's that simple. We have a string fileName. We call the .endsWith(".pdf") method on it, and it returns true because, well, the string literally ends with ".pdf".

Example 2: The "False" Scenario and Case Sensitivity
Let's see what happens when things don't match up.

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

    System.out.println("Ends with 'World!'? " + greeting.endsWith("World!")); // true
    System.out.println("Ends with 'world!'? " + greeting.endsWith("world!")); // false (case-sensitive)
    System.out.println("Ends with 'Hello'? " + greeting.endsWith("Hello"));   // false
}
Enter fullscreen mode Exit fullscreen mode

}
Output:

text
Ends with 'World!'? true
Ends with 'world!'? false
Ends with 'Hello'? false
Notice how the second check returned false because of the lowercase 'w'. The third check also fails because "Hello" is at the beginning of the string, not the end.

Leveling Up: Real-World Use Cases You'll Actually Encounter
Anyone can write a "Hello World" example. But where do you actually use this in a real project? Let's talk about some scenarios you'll definitely run into.

Use Case 1: File Type Validation and Processing
This is probably the most classic use case. You have a bunch of files, and you need to handle them differently based on their type.


java
public class FileProcessor {
    public static void main(String[] args) {
        String imageFile = "vacation_photo.jpg";
        String docFile = "report.docx";
        String pdfFile = "tutorial.pdf";

        processFile(imageFile);
        processFile(docFile);
        processFile(pdfFile);
    }

    public static void processFile(String filename) {
        if (filename.endsWith(".jpg") || filename.endsWith(".png")) {
            System.out.println(filename + " -> Sending to image compressor.");
        } else if (filename.endsWith(".pdf")) {
            System.out.println(filename + " -> Sending to PDF reader.");
        } else if (filename.endsWith(".docx")) {
            System.out.println(filename + " -> Opening with Word processor.");
        } else {
            System.out.println(filename + " -> Unknown file type. Skipping.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

text
vacation_photo.jpg -> Sending to image compressor.
report.docx -> Opening with Word processor.
tutorial.pdf -> Sending to PDF reader.
Imagine building a script to organize your downloads folder—this method would be the star of the show.

Use Case 2: Simple Input Validation and Sanitization
You're building a form, and you want to make sure a website URL or an email at least looks somewhat valid before you process it further.


java
import java.util.Scanner;

public class InputValidator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please enter your website URL: ");
        String userUrl = scanner.nextLine();

        // Basic validation
        if (!userUrl.endsWith(".com") && !userUrl.endsWith(".org") && !userUrl.endsWith(".in")) {
            System.out.println("Error: Please enter a valid URL (.com, .org, .in).");
        } else {
            System.out.println("Thank you! Processing URL: " + userUrl);
        }

        scanner.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

This is a lightweight, first line of defense for input validation. It's not foolproof, but it catches the most obvious mistakes.

Use Case 3: Routing Logic in Web Servers or Commands
In simpler applications or when parsing commands, you can use endsWith() to figure out what action to take.

java
public class CommandRouter {
    public static void main(String[] args) {
        String userCommand = "delete_user_123";

        if (userCommand.endsWith("_backup")) {
            System.out.println("Initiating backup procedure...");
        } else if (userCommand.startsWith("delete_user")) {
            System.out.println("Security: User deletion request detected.");
            // You could extract the user ID here for further processing
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Pro Tips and Best Practices: Don't Just Code, Code Well
Using endsWith() is easy, but using it effectively requires a bit of finesse. Here are some pro-tips to keep you out of trouble.

Always Check for null: This is the number one rookie mistake. Calling a method on a null string will throw a NullPointerException and crash your program.


java
String potentiallyNullString = getStringFromSomewhere(); // This might return null

// BAD: This can crash
// if (potentiallyNullString.endsWith(".txt")) { ... }

// GOOD: Defensive programming
if (potentiallyNullString != null && potentiallyNullString.endsWith(".txt")) {
    // Proceed safely
}
Enter fullscreen mode Exit fullscreen mode

Mind the Empty String (""): What happens if you check against an empty suffix?
"Hello".endsWith("") will always return true. This is by design in Java, but it's good to be aware of it so it doesn't cause unexpected behavior.

Case Sensitivity is a Thing: We've said it before, but it's worth repeating. If you need case-insensitive checks, convert the string to lowercase first.

java
String email = "My.Email@GMAIL.COM";
if (email.toLowerCase().endsWith("@gmail.com")) {
System.out.println("It's a Gmail address!");
}
It's Not a Full Regex: The endsWith() method checks for a literal character sequence. If you need the power of regular expressions (e.g., "ends with any number"), you'll need to use the matches() method instead. Don't try to force endsWith() to do a job it wasn't designed for.

Frequently Asked Questions (FAQs)
Q1: What does endsWith() return if the suffix is longer than the original string?
It returns false. For example, "hi".endsWith("hello") is false because "hi" is only 2 characters long and can't possibly end with the 5-character string "hello".

Q2: Can I use endsWith() with characters, not just strings?
Not directly. The parameter is a String. However, you can simply use a single-character string: myString.endsWith("A").

Q3: Is there a startsWith() method too?
Absolutely! It works exactly the same way but checks the beginning of the string. They are like the perfect coding siblings.

Q4: How does this compare to using substring() and equals()?
You could do myString.substring(myString.length() - suffix.length()).equals(suffix), but why would you? It's more code, less readable, and easier to make mistakes with index calculations. endsWith() is cleaner and more intention-revealing.

Wrapping Up: Why endsWith() is a Tool You'll Keep Using
The Java endsWith() method is a perfect example of a well-designed, single-responsibility tool. It does one job, and it does it perfectly. From validating file types to sanitizing user input, it’s a fundamental building block for writing clear, logical, and efficient Java code.

Mastering these core methods is what separates beginners from proficient developers. It's about knowing your toolkit inside and out.

Speaking of mastering skills, if you're looking to solidify your Java fundamentals and dive into professional software development, this is just the beginning. To learn professional software development courses such as Python Programming, Full Stack Development, and MERN Stack, visit and enroll today at codercrafter.in. We break down complex topics into bite-sized, understandable lessons with real-world projects that will build your portfolio and your confidence.

So go ahead, open up your IDE, and try playing with the endsWith() method. See what cool, practical uses you can find for it in your own projects.

Top comments (0)