
160 views
String endsWith()
The Java endsWith()
method is used to check whether a string ends with a specified suffix. It returns a boolean value, true
if the string ends with the specified suffix, and false
otherwise. The basic syntax of the endsWith()
method is as follows:
boolean result = originalString.endsWith(suffix);
originalString
: The string you want to check for the presence of the suffix.suffix
: The suffix you want to check for at the end of the original string.
Here’s an example of using the endsWith()
method:
public class EndsWithExample {
public static void main(String[] args) {
String text = "Hello, World";
boolean endsWithWorld = text.endsWith("World");
if (endsWithWorld) {
System.out.println("The string ends with 'World'.");
} else {
System.out.println("The string does not end with 'World'.");
}
}
}
In this example, the endsWith()
method is used to check if the text
string ends with the substring “World.” Since the string “Hello, World” ends with “World,” the result will be true
, and the program will print “The string ends with ‘World’.”
The endsWith()
method is frequently used to perform checks on strings, such as validating file extensions or identifying specific endings in text. It can be a helpful tool in various string manipulation tasks.