Write a program to Compare the strings using equals(), compareTo() and == operator


This is a Java program that demonstrates the use of the equals() method, the == operator, and the compareTo() method to compare strings.

  • The equals() method compares the contents of two strings and returns true if they are equal and false otherwise. In this program, str1.equals(str2) compares the contents of the str1 and str2 objects, while str1.equals(str1) compares the contents of the str1 object with itself.
  • The == operator compares the references of two objects and returns true if they are the same object and false otherwise. In this program, (str1 == str2) compares the references of the str1 and str2 objects, while (str1 == str1) compares the reference of the str1 object with itself.
  • The compareTo() method compares two strings lexicographically and returns an integer that indicates the order of the strings. If the first string is lexicographically less than the second string, the method returns a negative integer. If the first string is lexicographically greater than the second string, the method returns a positive integer. If the two strings are equal, the method returns 0. In this program, str1.compareTo(str2) compares str1 and str2, while str2.compareTo(str2) compares str2 with itself.

Source Code

public class Equals_CompareTo_Operator
{
	public static void main(String[] args)
	{
		String str1 = new String("Apple");
		String str2 = new String("Cherry");
 
		System.out.println("Comparing Strings using equals() Method..");
		System.out.println("String 1 and 2 : "+str1.equals(str2));
		System.out.println("String 1 and 1 : "+str1.equals(str1));
 
		System.out.println("Comparing Strings using == Operator..");
		System.out.println("String 1 and 2 : "+(str1 == str2));
		System.out.println("String 1 and 1 : "+(str1 == str1));
 
		System.out.println("Comparing Strings using compareTo() Method..");
		System.out.println("String 1 and 2 : "+str1.compareTo(str2));
		System.out.println("String 2 and 2 : "+str2.compareTo(str2));
	}
}

Output

Comparing Strings using equals() Method..
String 1 and 2 : false
String 1 and 1 : true
Comparing Strings using == Operator..
String 1 and 2 : false
String 1 and 1 : true
Comparing Strings using compareTo() Method..
String 1 and 2 : -2
String 2 and 2 : 0

Example Programs