How to write correct expression to result to Boolean? (Cannot cast from boolean to Boolean)

11,788

Solution 1

Are you looking for...

showDetailGroup = Boolean.valueOf( (mainGroupInt.intValue() != 0 && subGroupInt.intValue() != 0) || 
                                   (mainGroupInt.intValue() != 0 && showDetailGroup.booleanValue()) )

If not, I don't understand your question. The above code returns a Boolean representing the value of the boolean expression. See Java Boolean.valueOf() and Boolean.booleanValue() docs.

Solution 2

Boolean ( with capital B ) cannot be used in the boolean expressions without unboxing it.

If you want to silence the warning, convert Boolean to primitive type by calling booleanValue function (this is what's happening behind the scene with unboxing):

mainGroupInt.intValue() != 0 && showDetailGroup.booleanValue( )

Solution 3

Boolean and Integer are wrapper classes for the primitives boolean and int. You should change your variables to boolean and int and wrap them up later if you must pass them by reference to a function.

Share:
11,788
adis
Author by

adis

Web developer, JAVA & PHP

Updated on June 04, 2022

Comments

  • adis
    adis almost 2 years

    I am experiencing difficulties with an expression that should result in showing or hiding a band in an iReport.

    These are variables that I have:

    Integer mainGroupInt = Integer.valueOf(5);
    Integer subGroupInt = Integer.valueOf(5);
    Boolean showDetailGroup = Boolean.valueOf(false);
    

    The result must be a Boolean, so I tried the following:

    mainGroupInt.intValue() != 0 && subGroupInt.intValue() != 0)) || (mainGroupInt.intValue() != 0 && showDetailGroup)
    

    This is thus not working, I get the following error:

    The expression of type boolean is boxed into Boolean

    I'm overthinking this one but I cannot solve it.

    Thanks for your help.

  • adis
    adis about 12 years
    This does not work. It is giving an error on showDetailGroup if I try this.. The error is then: The expression of type Boolean is unboxed into boolean.
  • Sam DeHaan
    Sam DeHaan about 12 years
    @adis, I edited my answer. You need to convert the Boolean back to boolean as well, in the boolean expression (the .booleanValue() method). I hadn't noticed that initially.