Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - Finding the output (Q.No. 18)
18.
What will be the output of the program?
boolean bool = true; 
if(bool = false) /* Line 2 */
{
    System.out.println("a"); 
} 
else if(bool) /* Line 6 */
{
    System.out.println("b"); 
} 
else if(!bool) /* Line 10 */
{
    System.out.println("c"); /* Line 12 */
} 
else 
{
    System.out.println("d"); 
}
a
b
c
d
Answer: Option
Explanation:

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.

Discussion:
8 comments Page 1 of 1.

Karthi said:   1 decade ago
Why option A is not correct?

Aman said:   1 decade ago
Because If () block executes only when condition is true. We are assigning false value to bool so its not printing a.

Aleksey B said:   1 decade ago
This is not valid for Java.

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

Nisarga said:   1 decade ago
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:   1 decade ago
@Nigrasa.

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

Vivek Chennai said:   1 decade ago
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:   1 decade ago
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:   5 years ago
We will get Compiler Error at Line 2 due to assignment operator (=) because expected equality (==) operator.

Post your comments here:

Your comments will be displayed after verification.