equals() Java - Check whether two strings are equal

FacebooktwittertumblrFacebooktwittertumblr

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:

How To Call the Method:

Example:

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:

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.

 

 

FacebooktwittertumblrFacebooktwittertumblr

FacebooktwittertumblrFacebooktwittertumblr
Самоучители--узнать детальнее--