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
Joined: Nov 22, 2008
Posts: 18944
posted
0
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
Joined: Oct 31, 2003
Posts: 5
posted
0
Thnx for the reply. but why "if(flag=true)" is always true? Could u gimme clear picture? Thnx
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
Because flag=true is an assignment, not a comparison. Therefore it assigns true to flag and then returns the value of flag.