Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java String endsWith() method
Syntax and Examples



The endsWith() method in Java is your tool for determining whether a string concludes with a particular sequence of characters. It's handy for tasks like validating file extensions or checking if a URL ends with the expected domain.

Syntax

public boolean endsWith(String suffix)

Parameters

Parameter Description
suffix The string you want to check if the original string ends with. Can be null or empty.

Return Value

This method returns a boolean value:

  • true: If the string ends with the specified suffix.
  • false: Otherwise.

Examples

Checking File Extensions

Let's say you want to make sure a file has the '.txt' extension.

String filename = "myDocument.txt";
boolean hasTxtExtension = filename.endsWith(".txt");
System.out.println(hasTxtExtension); // Output: true
true

In this example, we check if the filename string ends with ".txt". Since it does, endsWith() returns true.

Empty Suffix

What happens when the suffix is an empty string?

String text = "Hello World";
boolean endsWithNothing = text.endsWith("");
System.out.println(endsWithNothing);
true

An empty suffix will always return true, as every string technically ends with nothing.

Case Sensitivity

The endsWith() method is case-sensitive. "java" and "JAVA" are different suffixes.

String myString = "Java Programming";
boolen endsWithJava = myString.endsWith("java");
boolen endsWithJAVA = myString.endsWith("JAVA");
System.out.println(endsWithJava); // Output: false
System.out.println(endsWithJAVA); // Output: false
false
false

Notice how both checks returned false because the capitalization doesn't match.

Null Suffix

Let’s see what happens when we provide a null suffix to the method.

String str = "This is a string";
boolen endsWithNull = str.endsWith(null);
System.out.println(endsWithNull);
true

If the suffix passed to endsWith() is null, then it returns true.

Comparing Parts of URLs

Imagine you're validating if a URL belongs to a specific domain.

String url = "https://www.example.com/path/to/resource";
boolean isExampleDomain = url.endsWith(".example.com");
System.out.println(isExampleDomain);
true

Here, we check if the url ends with ".example.com." This is a common technique for domain verification.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M