Huy Than
Huy Than

Reputation: 1556

Boolean and == vs =

The language is Java. Given this:

public static void main(String[] args) {
    Boolean b1 = true;
    Boolean b2 = true;
    int i1 = 1;

    if (b1 = true) //line 5
    if (b1 == true}  // line 6

I understand that b1 == true is a equivalent test , which will give the result : true OR false. However, with b1 = true , which to my understanding is a declaration, which should return nothing but in this case : b1 = true returns true, exactly the same as == test?

Can you explain why? Thanks!

Upvotes: 3

Views: 1305

Answers (3)

WtfMoment
WtfMoment

Reputation: 11

Well the reason both return true is simply because both expressions are true.

b1 = true is an assignment --> You tell java that b1 is true and when it evaluates it becomes true because here you simply say b1 is true.

b1 == true is a condition --> This is the line that makes some sense because you are now checking if [value of] b1 equals to true and this will evaluate to true or false depending on if b1 is true. Note that you could just write b1 because it's already a boolean (true or false).

I don't think you have realized it but you are using the object-type Boolean and not the primitive type boolean. You should stick to the one with a lowercase b if you don't really know the diffrence between object-based types and primtive types in Java.

btw I didn't know that Java allowed assignment to be used as a expression.

Upvotes: 1

Bharat Sinha
Bharat Sinha

Reputation: 14373

When you write

b1 = true;

true is assigned to b1.

When you write

if(b1 = true)

first the assignation is done and then the expression is evaluated and the expression evaluates to value of b1 i.e. true.

Upvotes: 1

Preet Kukreti
Preet Kukreti

Reputation: 8617

if (identifier = literal) evaluates to:

identifier = literal;  
if (identifier)

first you assign the literal to the identifier. then you test it post assignment

Upvotes: 15

Related Questions