StringBuilder equals() in Java

equals(): This method is available in java.lang.Object class of Java.

Syntax:

boolean java.lang.Object.equals(Object obj)

This method takes one argument of type Object (like StringBuilder object). This method indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.

2. It is symmetric: for any non-null reference values x and y, x.equals(y)should return true if and only if y.equals(x) returns true.

3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false provided no information used in equals comparisons on the objects is modified.

5. For any non-null reference value x, x.equals(null) should return false.

Parameters: One parameter is required for this method.

obj: the reference object with which to compare.

Returns: true if this object is the same as the obj argument; false otherwise.

Exceptions: NA

For Example:

StringBuilder str = new StringBuilder("Hello World")

StringBuilder obj = new StringBuilder("Hello World")

str.equals(obj) = > It returns false.

Approach

Java

public class Equals {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        StringBuilder obj = new StringBuilder("Hello World");
        System.out.println(str.equals(obj));
    }
}

Output:

false

No comments:

Post a Comment