Java String Endswith
## Java String endsWith() Method
The `endsWith()` method of the Java `String` class is used to test whether a string ends with a specified suffix. It is a highly efficient, built-in utility for performing suffix matching and validation.
---
### Syntax
```java
public boolean endsWith(String suffix)
```
### Parameters
* **`suffix`**: The character sequence (suffix) to be tested against the end of the string.
### Return Value
* Returns **`true`** if the character sequence represented by the argument is a suffix of the character sequence represented by this object; otherwise, it returns **`false`**.
* **Note:** The method will also return **`true`** if the argument is an empty string (`""`), or if it is exactly equal to this `String` object (as determined by the `equals(Object)` method).
---
### Code Example
The following example demonstrates how to use the `endsWith()` method to check the suffix of a given string.
```java
public class EndsWithExample {
public static void main(String[] args) {
String str = "Welcome to YouTip.com";
boolean retVal;
// Check if the string ends with "YouTip"
retVal = str.endsWith("YouTip");
System.out.println("Ends with 'YouTip'? " + retVal);
// Check if the string ends with "com"
retVal = str.endsWith("com");
System.out.println("Ends with 'com'? " + retVal);
// Check if the string ends with an empty string
retVal = str.endsWith("");
System.out.println("Ends with empty string? " + retVal);
}
}
```
#### Output
```text
Ends with 'YouTip'? false
Ends with 'com'? true
Ends with empty string? true
```
---
### Important Considerations
1. **Case Sensitivity**
The `endsWith()` method is **case-sensitive**. For example, `"document.PDF".endsWith(".pdf")` will return `false`. If you need a case-insensitive check, you can convert the string to lowercase first:
```java
String filename = "document.PDF";
boolean isPdf = filename.toLowerCase().endsWith(".pdf"); // Returns true
```
2. **NullPointerException**
If the `suffix` parameter is `null`, the method will throw a `NullPointerException`. Always ensure the suffix is not null before calling this method, or use defensive programming:
```java
if (str != null && suffix != null) {
boolean match = str.endsWith(suffix);
}
```
3. **Performance**
The `endsWith()` method internally uses the `startsWith()` method with an offset. It is highly optimized and runs in $O(K)$ time complexity, where $K$ is the length of the suffix.
YouTip