Java: String equals(Object anObject) method

In this article, we will discuss string comparison using String’s equals() method


equals(Object anObject) method:

  • This String method is used to perform string comparison
  • Note: This String comparison is case-sensitive, there is one more variation to this equals() method i.e.; equalsIgnoreCase(), which is case-insensitive

Method Signature:

public boolean equals(Object anObject);


Returns a boolean value either true or false

  • True –> if both string contents are equal, considering CASE differences
  • False –> if both string contents are NOT equal, considering CASE differences


Examples on equals() method:

  • String comparison program using equals() method

package in.bench.resources.string.methods;

public class StringEqualsMethod {

	public static void main(String[] args) {

		// string literal and objects
		String str1 = "bench";
		String str2 = new String("bench");
		String str3 = new String("BENCH");

		// comparing string literal and string object
		boolean bool1 = str1.equals(str2);

		// printing to the console
		System.out.println("str1 & str2 are equal ? : " + bool1);

		// comparing string literal and string object
		boolean bool2 = str1.equals(str3);

		// printing to the console
		System.out.println("str2 & str3 are equal ? : " + bool2);

		// in-line equality check
		System.out.println("str1 & oracle are equal ? : " 
				+ str1.equals("oracle"));


str1 & str2 are equal ? : true
str2 & str3 are equal ? : false
str1 & oracle are equal ? : false




Happy Coding !!
Happy Learning !!

Java: String equalsIgnoreCase(Object anObject) method
Java: String endsWith(String suffix) method