aspose file tools*
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "if_else" Watch "if_else" New topic
Author

if_else

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) {
System.out.println("true");
} else {
System.out.println("false");
}

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,
Ash
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
You are correct. That is why normally you would state it like
if(flag){
//whatever
}
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;
flag=true;
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...
Cheers,
Ravindra Mohan
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: if_else