Introduction String comparison in Java

java string compare can be done in many ways as shown below. Depending on the type of java string compare you need, each of them is used.

There are three ways to compare String objects:

  • By = = operator
  • By equals() method
  • By compareTo() method

Comparing using the == Operator

The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the == operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to

				
class Testcomparison {
	public static void main(String args[]) {
		String s1 = "Mithilesh";
		String s2 = "Mithilesh";
		String s3 = new String("Mithilesh");
		System.out.println(s1 == s2);// true (because both refer to same
										// instance)
		System.out.println(s1 == s3);// false(because s3 refers to instance
										// created in nonpool)
	}
}

	
Output:true
       false
       

By equals() method

equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:

public boolean equals(Object another){} compares this string to the specified object.

public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.

 class Teststringcomparison {
	public static void main(String args[]) {
		String s1 = "Mithilesh";
		String s2 = "Mithilesh";
		String s3 = new String("Mithilesh");
		String s4 = "Rahul";
		System.out.println(s1.equals(s2));// true
		System.out.println(s1.equals(s3));// true
		System.out.println(s1.equals(s4));// false
	}
}
Output:true
       true
       false
       

   
 class Teststringcomparison2 {
	public static void main(String args[]) {
		String s1 = "Mithilesh";
		String s2 = "MITHILESH";

		System.out.println(s1.equals(s2));// false
		System.out.println(s1.equalsIgnoreCase(s3));// true
	}
}

Comparing using the compareTo Method

compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.

public class StringComparision3 {

	public static void main(String[] args) {
		String name1 = "moon";
		String name2 = new String("cob");
		String name3 = "Moon";
		// 1st case
		if (name1.compareTo(name2) == 0) {
			System.out.println("The strings are equal.");
		} else if (name1.compareTo(name2) < 0) {
			System.out.println("name2 follows name1");
		} else {
			System.out.println("name1 follows name2");
		}
		// 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case
		if (name1.compareTo(name3) == 0) {
			System.out.println("The strings are equal.");
		} else if (name1.compareTo(name3) < 0) {
			System.out.println("name3 follows name1");
		} else {
			System.out.println("name1 follows name3");
		}
	}
}