Java Programming - Flow Control - Discussion

Discussion :: Flow Control - Finding the output (Q.No.18)


What will be the output of the program?

boolean bool = true; 
if(bool = false) /* Line 2 */
else if(bool) /* Line 6 */
else if(!bool) /* Line 10 */
    System.out.println("c"); /* Line 12 */

[A]. a
[B]. b
[C]. c
[D]. d

Answer: Option C


Look closely at line 2, is this an equality check (==) or an assignment (=). The condition at line 2 evaluates to false and also assigns false to bool. bool is now false so the condition at line 6 is not true. The condition at line 10 checks to see if bool is not true ( if !(bool == true) ), it isn't so line 12 is executed.

Karthi said: (Jul 20, 2011)  
Why option A is not correct?

Aman said: (Sep 15, 2011)  
Because If () block executes only when condition is true. We are assigning false value to bool so its not printing a.

Aleksey B said: (Oct 12, 2012)  
This is not valid for Java.

Line2 will cause compillation error, there is no such an option in the answers section.

Nisarga said: (Jun 23, 2013)  
But the if() block at line 2 has no condition to be checked as the statement is an assignment statement. So the if block should also get executed.

Sudhanshu said: (Jul 9, 2013)  

I too think so because back there it was a same situation and the if Clause was getting executed!

Vivek Chennai said: (Jan 4, 2014)  
Guys I think you forget to see that = sign in Line 2, it is a assignment operator not a equal to operator. In java if block executes only if some conditions are satisfied otherwise it won't execute if block section.

Yaitloutou said: (Feb 1, 2014)  
An assignment expression has a return value, which is the value that's assigned to the variable.

Therefore the expression (bool=false) within the first IF's statement is evaluated as false.

Panshul Sharma said: (May 11, 2020)  
We will get Compiler Error at Line 2 due to assignment operator (=) because expected equality (==) operator.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.