Alex Rivera | Logout

Getting confused with == and = in "if" statement

Asked 2010-03-06T20:18:41.417
12

I know that we cant use assignment operator in if statements in java as we use in any other few languages.

that is

            int a;

            if(a = 1) {  } 

will give a compilation error.

but the following code works fine, how?

           boolean b;

           if(b = true) {   }

EDIT : Is this the exception to rule that assignment cant be used in if statement.

Edit
Report

1 Answer

10

For if you need an expression that evaluates to boolean. b = true evalueates to boolean but a = 1 evaluates to int as assignments always evaluate to the assigned values.

answered 2010-03-06T20:20:24.253

Your Answer