hi guys, could anyone explain this to me: it prints out 'true':
boolean flag = false; if (flag = true) { System.out.println("true"); } else { System.out.println("false"); } }
the if clause accepts a boolean right,then how can the assignment operator be used???
thanx a lot. prasanthi
Manish Singhal
Ranch Hand
Joined: Sep 21, 2000
Posts: 104
posted
0
if constructs certainly accepts boolean but this is an exceptional case for boolean. Assignment operator can be used in if constructs if the operand is boolean and hence the expression becomes boolean (true/false depending upon assignment). regds, Manish
Sudhir Bangera
Ranch Hand
Joined: Oct 10, 2000
Posts: 50
posted
0
Hi Prasanthi, You are right about if clause accepting boolean, what is happening here is, the assignment operation takes place first and thus the if clause becomes --> if (flag) where flag has become true due to the assignment and hence it prints out true. If flag was of type int and if assignment inside the if clause is something like --> if (flag = 0) then you will get compiler error but in the example given it is perfectly legal. Hope this helps......
prasanthi kothapa
Ranch Hand
Joined: Oct 19, 2000
Posts: 30
posted
0
thanks a lot manish and sudhir.that was an immediate reply. prasanthi