Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between matches and equalsIgnoreCase or equals in string class

matches: Will check if the complete string entered is equal to the value present in the string object.

equalsIgnoreCase: Ignoring the case, it checks if the string entered is equal to the value present in the string object.

equals: Case sensitive and it checks if the string entered is equal to the value present in the string object.

This is what I know about the methods, present in String class.

Are there any other differences(Am I missing any valuable differences)?

If there are no differences, then why cant matches method be removed from String class, since the functionality it puts forth can be achieved using the other above mentioned methods, appropriately.

like image 583
Anuj Balan Avatar asked Mar 14 '12 10:03

Anuj Balan


2 Answers

There is a big difference - matches checks the match of a String to a regular expression pattern, not the same string. Do not be mislead by the fact that it receives a String as an argument.

For example:

"hello".equals(".*e.*"); // false
"hello".matches(".*e.*"); // true
like image 123
MByD Avatar answered Oct 06 '22 06:10

MByD


The key difference is that matches matches a regular expressions whereas equals matches a specific String.

System.out.println("hello".matches(".+"));    // Output: true
System.out.println("hello".equals(".+"));     // Output: false
System.out.println("wtf?".matches("wtf?"));   // Output: false
System.out.println("wtf?".equals("wtf?"));    // Output: true

I suggest you have a look at what a regular expression is

like image 26
Peter Lawrey Avatar answered Oct 06 '22 06:10

Peter Lawrey