- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java String comparison, differences between ==, equals, matches, compareTo().
The equals() method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Example
public class Sample{ public static void main(String []args){ String s1 = "tutorialspoint"; String s2 = "tutorialspoint"; String s3 = new String ("Tutorials Point"); System.out.println(s1.equals(s2)); System.out.println(s2.equals(s3)); } }
Output
true false
You can also compare two strings using == operator. But, it compares references of the given variables not values.
Example
public class Sample { public static void main(String []args) { String s1 = "tutorialspoint"; String s2 = "tutorialspoint"; String s3 = new String ("Tutorials Point"); System.out.println(s1 == s2); System.out.println(s2 == s3); } }
Output
true false
The matches() method of the String class tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str).
Example
import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); System.out.print("Return Value :" ); System.out.println(Str.matches("(.*)Tutorials(.*)")); System.out.print("Return Value :" ); System.out.println(Str.matches("Tutorials")); System.out.print("Return Value :" ); System.out.println(Str.matches("Welcome(.*)")); } }
Output
Return Value :true Return Value :false Return Value :true
- Related Articles
- What is the difference between equals and compareTo in Java?
- Java String compareTo() method
- Java String compareTo() Method example.
- What are the differences between compareTo() and compare() methods in Java?\n
- Java String equals() method.
- Java String Comparison Methods.
- String Comparison in Java
- Java String equals() method example.
- String compare by compareTo() method in Java
- Java Program to compare string using compareTo() method
- Case sensitive string comparison in Java.
- Java string comparison sample code examples
- String compare by equals() method in Java
- Difference between == and equals() method in Java.
- Difference between equals() vs equalsIgnoreCase() in Java

Advertisements