⬅ Previous Topic
Java StringcopyValueOf()
methodNext Topic ⮕
Java Stringequals()
methodendsWith()
method⬅ Previous Topic
Java StringcopyValueOf()
methodNext Topic ⮕
Java Stringequals()
methodThe 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.
public boolean endsWith(String suffix)
Parameter | Description |
---|---|
suffix |
The string you want to check if the original string ends with. Can be null or empty. |
This method returns a boolean
value:
true
: If the string ends with the specified suffix.false
: Otherwise.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
.
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.
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.
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.
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.
⬅ Previous Topic
Java StringcopyValueOf()
methodNext Topic ⮕
Java Stringequals()
methodYou 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.