This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: if_else