In this tutorial, you will learn about String equals() method, its syntax, and usage with examples.

Java String equals() method

In Java, String equals() method takes an object as argument, and checks if the given argument is equal to the string.

Syntax of equals()

The syntax to call String equals() method in Java is

string.equals(obj)

equals() has a single parameter.

ParameterDescription
obj[Mandatory]An Object type value. In other words, we can pass object of any type.The value which is checked with the string for equality.

equals() returns value of boolean type.

ADVERTISEMENT

Examples

1. equals() – The string is equal to the argument object

In this example, we take two strings: string and obj; and check if the string is equal the string obj using String equals() method. We have taken the string values such that string equals obj.

Java Program

public class Main {
	public static void main(String[] args) {
		String string = "Apple";
		String obj = "Apple";
		
		if (string.equals(obj)) {
			System.out.println("Given strings are EQUAL.");
		} else {
			System.out.println("Given strings are NOT EQUAL.");
		}
	}
}

Output

Given strings are EQUAL.

Since string equals obj, the equals() method returns true, and the if-block is run.

2. equals() – The string is not equal to the argument object

In this example, we take two strings: string and obj such that the value in string variable is not equal to the value in obj.

Java Program

public class Main {
	public static void main(String[] args) {
		String string = "Apple";
		String obj = "Banana";
		
		if (string.equals(obj)) {
			System.out.println("Given strings are EQUAL.");
		} else {
			System.out.println("Given strings are NOT EQUAL.");
		}
	}
}

Output

Given strings are NOT EQUAL.

Since string does not equal obj, the equals() method returns false, and the else-block is run.

Conclusion

In this Java String Methods tutorial, we have seen about String equals() method in Java, its syntax, and how to use String equals() method in Java programs with the help of examples.