In Java, endsWith() checks whether a string ends with a given suffix. It returns true or false.
You pass the suffix. It is required. The check is case-sensitive by default.
Syntax
Call endsWith on the string. Start with this line.
java
boolean ok = file.endsWith(".java");
Call
What it does
file.endsWith(".java")
Returns true when file ends with .java.
This only checks the end. For a match anywhere, use contains().
Library declarations
java
public boolean endsWith(String suffix);
Parameters
Parameter
Description
suffix
Required. The ending text to look for. Do not pass null.
Return Value
Return Value
Description
true
The string ends with the suffix.
false
The string does not end with the suffix.
Java Examples
Example 1 — Basic Suffix Check
Test whether a greeting ends with a known word.
java
public class EndsWithBasic {
public static void main(String[] args) {
String text = "Hello, Java!";
System.out.println(text.endsWith("Java!"));
System.out.println(text.endsWith("Hello"));
}
}
Output
true
false
How It Works
Store the text.text ends with "Java!".
First check.endsWith("Java!") matches the last five characters → true.
Second check."Hello" is at the start, not the end → false.
Boolean result. Use it directly in println or an if.
Example 2 — Check a File Extension
A common real use: accept only .java source files.
java
public class EndsWithFile {
public static void main(String[] args) {
String file = "Main.java";
if (file.endsWith(".java")) {
System.out.println("Java source file");
} else {
System.out.println("Not a .java file");
}
}
}
Output
Java source file
How It Works
Read the name.file is "Main.java".
Test the suffix.endsWith(".java") looks only at the end.
Branch on the result.true prints the success message.
Keep the dot. Include . in the suffix so "xjava" does not match by accident.
Example 3 — Case Sensitivity
endsWith is case-sensitive. Normalize both sides when extensions may vary in case.
java
public class EndsWithCase {
public static void main(String[] args) {
String file = "Report.PDF";
System.out.println(file.endsWith(".pdf"));
System.out.println(file.toLowerCase().endsWith(".pdf"));
}
}
Output
false
true
How It Works
Exact match fails."PDF" ≠ "pdf" → first line is false.
Lowercase the string.toLowerCase() turns it into "report.pdf".
Check again. Now endsWith(".pdf") succeeds → true.
Keep the suffix lower too. Compare against a lowercase suffix after normalizing.
Frequently Asked Questions
endsWith() checks whether a string ends with a given suffix and returns true or false.
suffix is required.
Yes by default.
An empty suffix always returns true.
endsWith() only checks the end. contains() looks anywhere.