Java Tutorial Java Advanced Java References

Java String - equals() Method



The Java equals() method is used to compare the object against the given string. It returns true if the given object represents a string equivalent to given string, else returns false.

Syntax

public boolean equals(Object obj)

Parameters

obj specify the object to compare against given string.

Return Value

Returns true if the given object represents a string equivalent to given string, else returns false.

Exception

NA.

Example:

In the example below, equals() method is used to compare the string objects against the given string.

public class MyClass {
  public static void main(String[] args) {
    String str1 = "Hello World";
    String str2 = "Hello World";
    String str3 = "Hello";

    System.out.println(str1.equals(str2)); 
    System.out.println(str1.equals(str3)); 
  }
}

The output of the above code will be:

true
false

Example:

In the example below, equals() method is used to compare the objects against the given string.

public class MyClass {
  public static void main(String[] args) {
    String str1 = "Java";
    Object str2 = "Java";
    Object str3 = "Python";

    System.out.println(str1.equals(str2)); 
    System.out.println(str1.equals(str3)); 
  }
}

The output of the above code will be:

true
false

❮ Java String Methods