File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes the if  clause Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "the if  clause" Watch "the if  clause" New topic
Author

the if clause

prasanthi kothapa
Ranch Hand

Joined: Oct 19, 2000
Posts: 30
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

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
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
thanks a lot manish and sudhir.that was
an immediate reply.
prasanthi
Manish Singhal
Ranch Hand

Joined: Sep 21, 2000
Posts: 104
u r most welcome prasanthi
Manish
 
IntelliJ Java IDE
 
subject: the if clause
 
Threads others viewed
= Operator
if_else
doubt
easy question
simple question
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture