Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
string
endswith
communitycreator

What is the String.endsWith() method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

We can use the String.endsWith() method to see if a string ends with a specific string.

Syntax

stringObj.endsWith(str);

This method will return true if the string object ends with the passed string argument; otherwise, it returns false.

Example

class HelloWorld {
public static void main( String args[] ) {
String str = "JavaScript";
System.out.print( "Checking if " + str + " ends with Script -- " );
System.out.println( str.endsWith("Script") ); // true
System.out.print( "Checking if " + str + " ends with pt -- " );
System.out.println( str.endsWith("pt") ); // true
System.out.print( "Checking if " + str + " ends with script -- " );
System.out.println( str.endsWith("script") ); // false -- because case sensitive
}
}

In the code above, we created the “JavaScript” string and:

  • Checked if the JavaScript string ends with Script. In this case, the endsWith method returns true because the JavaScript string ends with Script.

  • Checked if JavaScript string ends with pt. In this case, the endsWith method returns true because the JavaScript string ends with pt.

  • Checked if JavaScript string ends with script. In this case, the endsWith method returns false because the JavaScript string ends with Script, not script. The endsWith method is case-sensitive, so S is not equal to s.


Points to note

  • The endsWith method is a case-sensitive method.

  • If we pass null as an argument to the endsWith method, then we will get NullPointerException.

  • The endsWith method does not handle regex. If we pass the regex as an argument, it is treated as a normal string.

RELATED TAGS

java
string
endswith
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring