user3367285
user3367285

Reputation: 31

Comparing primative booleans in if statements

In terms of primitive booleans, what is the difference between

if(someBoolean == false){}

and

if(someBoolean = false){}

I wrote the latter (in Eclipse) expecting an error to be thrown but none was.

Upvotes: 0

Views: 59

Answers (5)

vineeth sivan
vineeth sivan

Reputation: 510

if(someBoolean = false){}

the above statement first assign the value to the boolean variable and then condition checking is done. There is no error in the statement.

if(someBoolean == false){}

This statement will only do condition checking.

Upvotes: 0

Hong
Hong

Reputation: 3

someBoolean == false is comparing that returns a boolean value someBoolean = false is assinging that returns a boolean value as well

Upvotes: 0

starkshang
starkshang

Reputation: 8558

if(someBoolean=false) will set false to someBoolean then return someBoolean,then if statement judge the someBoolean value,so it will compiles well.

But such code won't compile:

int val = 2;
if(val = 3){
}

it will compile error:

InCompatible Types:Required:boolean,Found

because its return value is int,can't be changed to boolean type which if statement needs.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172528

== is used for comparison

= is used for assingnment.

So in your first case you are comparing the values and in the second case you are assigning. Both of the statement will compile and execute successfully.

However if are looking for an effective way to use that inside an if statement then you can simply do as:

if(someBoolean)   //for checking true

and

if(!someBoolean)   //for checking false

Upvotes: 1

Chris Jaquez
Chris Jaquez

Reputation: 669

someBoolean = false assigns the value of false to that boolean, rather than actually comparing if it is false or not.

= assigns

== compares

Upvotes: 0

Related Questions