Home > Enterprise >  How to compare object type with boolean
How to compare object type with boolean

Time:08-24

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?

CodePudding user response:

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)) {
    ...
}

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • java
  • Related