equals not working with same value with different datatype

I have two objects as below:

Object obj1 = new BigDecimal(123);
Object obj2 = new Long(123);

if(obj1.equals(obj2))
 System.out.println("both are equal");
else
 System.out.println("both are not equal");

it is showing that both are not equal. Is it comparing based on datatype?

Jon Skeet
people
quotationmark

Is it comparing based on datatype?

Yes, exactly as it's documented to. From BigDecimal.equals:

Returns true if and only if the specified Object is a BigDecimal whose value and scale are equal to this BigDecimal's.

And from Long.equals:

The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object.

It's very rarely a good idea for objects of different types to compare equal to each other - typically in an equals implementation you'll have something like:

if (getClass() != other.getClass()) {
    return false;
}

Or if your class is final, you can just use:

if (!(other instanceof MyClass)) {
    return false;
}

people

See more on this question at Stackoverflow