misco
misco

Reputation: 1952

Why Boolean TRUE is not TRUE?

I discover during debbuging my android app the strange behaviour.

There is expression:

if (r == true)

where var r has the value true but the whole statement is false. I try to use object Boolean and also primitive type boolean.

I'm sure that I make some basic mistake.

Here is the screen from debbuger.

enter image description here

Edit:

I'm using java.lang.Boolean.

method isSyncRequired returns Boolean.TRUE and it is compared in if-else block.

if(isSyncRequired(s))
if (r)
if (r == true)

dont't work.

Upvotes: 2

Views: 398

Answers (3)

danijel
danijel

Reputation: 576

You should unbox the Boolean value. Try

if (r.booleanValue())

or

if (r.booleanValue() == true)

Upvotes: 1

John Leehey
John Leehey

Reputation: 22240

== compares by reference. You are comparing a Boolean object to a boolean value.

Use if (r) instead.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198481

Because you're using a capital-B Boolean, which is an object, so == uses reference equality semantics.

What you should be doing is just

if (r)

There's no need to test if it's equal to true. Or inline it:

if (isSyncRequired(s)) {

Upvotes: 11

Related Questions