fahadhub
fahadhub

Reputation: 225

How to compare object type with boolean

import java.util.HashMap;

public class file{
    
    public static void main(String args[]){
        Object a;
        a = true;
        if (a == true){
            System.out.println("Yes");
        }
    }
}

I get the error error: incomparable types: Object and boolean

I was to compare object a which stores a boolean value with an actual boolean type. How do I do that?

Upvotes: 3

Views: 608

Answers (3)

Aashish Dalmia
Aashish Dalmia

Reputation: 21

Try this - if (Boolean.TRUE.equals(a)) { ... }

Upvotes: 2

vsfDawg
vsfDawg

Reputation: 1527

You are comparing an Object reference to a primitive boolean - the types are not compatible for the equality operator (==). You should generally avoid using == with objects unless you really want to check if it is the same reference.

Prefer the equals method to compare objects.

if (Boolean.TRUE.equals(a)) { ... do stuff ... }

Note that we are invoking the method on a statically defined instance and passing the variable to be tested as the argument. The method will handle null arguments and incorrect type arguments (it will return false) so you don't have to.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

This happens because boolean primitive true is boxed for conversion to Object. You need to compare it to another boxed object, like this

if (a == Boolean.TRUE) {
    ...
}

or like this

if (a.equals(true)) {
    ...
}

Upvotes: 7

Related Questions