java.lang.Boolean equals(Object obj)

Description

Based from the official documentation of Oracle, the equals method of Boolean class compares this Boolean object against the specified object method rrgument. The result is true if and only if the argument is not null and is a Boolean object that represents a float with the same value as the float represented by this object.

Important Notes:

  • overrides equals in class Object

Method Syntax

public boolean equals(Object obj)

Method Argument

Data Type Parameter Description
Object obj the object to compare with.

Method Returns

The equals(Object obj) method of Boolean class 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.

Discussion

Normally in dealing with primitive type boolean we test equality by using == operators. This will no longer true if we are dealing with Boolean wrapper class because inherently to test two object equality we have to use the equals which is by default being inherited by all java objects from class Object.

		Boolean f1 = true;
		Boolean f2 = true;
		System.out.println(f1==f2);

Normally if the above code declaration uses float primitive type, the result would be true however since the boolean value true  is assigned to wrapper class Boolean, it would print out false. If we wanted to use the == operator instead of equals, then we need to convert the Boolean values using the booleanValue() method of Boolean class.

		f1.booleanValue() == f2.booleanValue()

The above code snippet would result to true.

Java Boolean equals(Object obj) Example

Below is a simple java example on the usage of equals(Object obj) method of Boolean class.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * equals(Object obj) method of Boolean class.
 */

public class BooleanEqualsExample {

	public static void main(String[] args) {	
		
		// instantiate a Boolean
		Boolean bool = new Boolean(true);
		
		// instantiate an Object
		Object obj = new Boolean(true);
		
		// test equality of the two value
		if(bool.equals(obj)){
			System.out.println("they are equal using equals test");
		}
		else{
			System.out.println("they are not equal using equals test");
		}
		

		// test equality of the two value using ==
		if(bool==obj){
			System.out.println("they are equal using == test");
		}
		else{
			System.out.println("they are not equal using == test");
		}
		
		
	}

}

Basically on the above example, we have declared three boolean values. We then compared all three values with each other and printed the result on the console.

Sample Output

Below is the sample output when you run the above example.

java Boolean equals() example output