equals() Java - Check whether two strings are equal
equals() in Java
The equals() method checks whether two objects are equal (for example, two strings). The method works for all main classes in Java.
Syntax:
1 |
public boolean equals(Object o) |
How To Call the Method:
1 |
boolean b = str1.equals(str2); |
Example:
1 2 3 4 5 6 7 8 9 10 11 |
public class Test { public static void main(String args[]) { String str1 = "Good morning"; String str2 = "Good morning"; String str3 = "Good evening"; System.out.println("String '" + str1 + "' equals '" + str2 + "' : " + str1.equals(str2)); System.out.println("String '" + str1 + "' equals '" + str3 + "' : " + str1.equals(str3)); } } |
If you run this code on your computer, you will see the following in the console:
Commentary:
There are 3 strings:
- "Good morning"
- "Good morning"
- "Good evening"
As you see, the first 2 strings have the same text "Good morning". The 3rd string has another text "Good evening".
That's why when we compared the first 2 strings with the help of the equals() method, we've got true in the console. But when we compared the 1st string with the 3rd string, we've got false.
Please note, that if we compare 2 different objects (for example, the number 10 and the string "10"), we'll get false:
1 2 3 4 5 6 7 8 9 |
public class Test { public static void main(String args[]) { String str1 = "10"; Integer i = 10; System.out.println("String '" + str1 + "' equals '" + i + "' : " + str1.equals(i)); } } |
If you run this code on your computer, you will see the following in the console:
Please note, that there is another method called compareTo() which also can compare objects, for example, strings. Nevertheless, the equals() method and the compareT0() method are different:
- equals() - returns boolean (true, false)
- compareTo() - returns int data type.
That's it for this article. You can find more articles in our Java Tutorial for Beginners.