File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes if_else Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "if_else" Watch "if_else" New topic


Ash sav
Ranch Hand

Joined: Apr 14, 2001
Posts: 55
What is the result of executing the following fragment of code:

boolean flag = false;
if (flag = true) {
} else {

true is printed to standard out
false is printed to standard out
An exception is raised
Nothing happens
Answer is true is printed
I know in If clause it always uses == sign for comparison not a = So is that means in above question they assign true value to false. If I'm wrong please correct me.
Thanks in advance,
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
You are correct. That is why normally you would state it like
The the actual value of flag is evaluated.

"JavaRanch, where the deer and the Certified play" - David O'Meara
atul kashyap
Ranch Hand

Joined: Mar 22, 2001
Posts: 34
boolean flag = false;
if (flag = true) { System.out.println("true");}
else { System.out.println("false");}
this is equivalent to :
boolean flag=false;
if (flag) {System.out.println("true");}
else {System.out.println("false");}
which obviously gives "true" as output.
First the assignment is made to the boolean variable flag and then it's value is used in the if construct.
Please correct me if I am wrong
Ravindra Mohan
Ranch Hand

Joined: Mar 16, 2001
Posts: 216
Folks you are right...
Ravindra Mohan
I agree. Here's the link:
subject: if_else
It's not a secret anymore!