Returns false if not ending with the specified string.
public boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
public class StringEndswithExample { public static void main(String[] args) { String input1 = "java"; String input2 = "w3schools"; String input3 = "java-w3schools.blogspot.com"; System.out.println("input1.endsWith(\"va\") :: "+input1.endsWith("va")); System.out.println("input2.endsWith(\"schools\") :: "+input2.endsWith("schools")); System.out.println("input2.endsWith(\"blogspot.com\") :: "+input3.endsWith("blogspot.com")); } }
input1.endsWith("va") :: true input2.endsWith("schools") :: true input2.endsWith("blogspot.com") :: true
package examples.java.w3schools.string;
public class EndswithDomainChecker {
public static void main(String[] args) {
String domain1 = "https://en.wikipedia.org";
String domain2 = "java-w3schools.blogspot.com";
String domain3 = "oracle.java";
System.out.println("Checking Domain 1 : "+checkDomain(domain1));
System.out.println("Checking Domain 2 : "+checkDomain(domain2));
System.out.println("Checking Domain 3 : "+checkDomain(domain3));
}
private static String checkDomain(String domainName) {
if (domainName.endsWith(".com")) {
return "Valid domain " + domainName;
} else if (domainName.endsWith(".org")) {
return "Valid domain " + domainName;
} else if (domainName.endsWith(".net")) {
return "Valid domain " + domainName;
}
return "Invalid domain " + domainName;
}
}
Checking Domain 1 : Valid domain https://en.wikipedia.org Checking Domain 2 : Valid domain java-w3schools.blogspot.com Checking Domain 3 : Invalid domain oracle.java
public boolean endsWith(String suffix) { return startsWith(suffix, length() - suffix.length()); }
endsWith method calls internally startsWith method by passing specified string and input_string.length - specified_string.length.
specified string: w3schools and specified_string.length = 8
startsWith("w3schools", 13-8); --> startsWith("w3schools", 5)
So, it searches in the input_string from position or index 5 to till end for the specified_string. If found then returns true, otherwise false.
Please post your questions in the comment section.
No comments:
Post a Comment
Please do not add any spam links in the comments section.