Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

if_else

 
Ash sav
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct. That is why normally you would state it like
if(flag){
//whatever
}
The the actual value of flag is evaluated.
 
atul kashyap
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Folks you are right...
Cheers,
Ravindra Mohan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic