Java - Boolean equals() method



Description

The Java Boolean equals(Object obj) returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

Declaration

Following is the declaration for java.lang.Boolean.equals() method

public boolean equals(Object obj)

Overrides

equals in class Object

Parameters

obj − the object to compare with

Return Value

This method returns true if the Boolean objects represent the same value, false otherwise.

Exception

NA

Example 1

The following example shows the usage of Boolean equals() method with Boolean objects.

package com.tutorialspoint;
public class BooleanDemo {
   public static void main(String[] args) {

      // create 2 Boolean objects b1, b2
      Boolean b1, b2;

      // create a boolean primitive res
      boolean res;

      // assign values to b1, b2
      b1 = Boolean.valueOf(true);
      b2 = Boolean.valueOf(false);

      // assign the result of equals method on b1, b2 to res
      res = b1.equals(b2);

      String str = "b1:" +b1+ " and b2:" +b2+ " are equal is " + res;

      // print res value
      System.out.println( str );
   }
}

Output

Let us compile and run the above program, this will produce the following result −

b1:true and b2:false are equal is false

Example 2

The following is another example to show the usage of Boolean equals() method with a primitive value.

package com.tutorialspoint;
public class BooleanDemo {
   public static void main(String[] args) {

      // create 2 Boolean objects b1, b2
      Boolean b1, b2;

      // create a boolean primitive res
      boolean res;

      // assign values to b1, b2
      b1 = Boolean.valueOf(true);
      b2 = false;

      // assign the result of equals method on b1, b2 to res
      res = b1.equals(b2);

      String str = "b1:" +b1+ " and b2:" +b2+ " are equal is " + res;

      // print res value
      System.out.println( str );
   }
}

Output

Let us compile and run the above program, this will produce the following result −

b1:true and b2:false are equal is false

Example 3

The following is another example to show the usage of Boolean equals() method with a null value.

package com.tutorialspoint;
public class BooleanDemo {
   public static void main(String[] args) {

      // create 2 Boolean objects b1, b2
      Boolean b1, b2;

      // create a boolean primitive res
      boolean res;

      // assign values to b1, b2
      b1 = Boolean.valueOf(true);
      b2 = null;

      // assign the result of equals method on b1, b2 to res
      res = b1.equals(b2);

      String str = "b1:" +b1+ " and b2:" +b2+ " are equal is " + res;

      // print res value
      System.out.println( str );
   }
}

Output

Let us compile and run the above program, this will produce the following result −

b1:true and b2:null are equal is false
java_lang_boolean.htm
Advertisements