Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equality test for boolean

 
lakshmisreenivas karri
Greenhorn
Posts: 5
  • 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");
}
}

A. true is printed to standard out
B. false is printed to standard out
C. An exception is raised
D. Nothing happens
E. Compile error
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karri
The if(flag=true) always is true, there is not a compile error because flag is a boolean. So the answer is A.
 
lakshmisreenivas karri
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thnx for the reply.
but why "if(flag=true)" is always true?
Could u gimme clear picture?
Thnx
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because flag=true is an assignment, not a comparison. Therefore it assigns true to flag and then returns the value of flag.
 
lakshmisreenivas karri
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I'm seeing it as an assignment but still i was stucked.
Ofcourse i got it now.
Thnx anyway.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic