Java equals method to compare strings

The equals method in Java

The equals method of the String class is used to compare two strings whether two are the same or not.

A few main points about equals Java method are:

  • The Java equals method is used to compare two strings.
  • In the equals method, the strings are compared as case-sensitive i.e. “Java” and “java” are different words.
  • The return result is True if strings are the same.
  • The return result will be False if strings are not the same.

Syntax of string equals method

The syntax of equals method is:

Strex.equals(Strex2)

Where Strex and Strex2 are two strings being compared.

Example of using equals method

The example below uses Java equals method that compares two strings. Total three string objects are used and compared in two Boolean variables with the equals method. See the result below:

Experience this online

The output will be:

String 1 and 2 are equal? false

String 1 and 2 are equal? True

The first result is false as ‘s’ is small in the first string. As such, the equals method compares the strings as case-sensitive.

Also see: Java strings