Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - General Questions (Q.No. 1)
1.
public void foo( boolean a, boolean b)
{ 
    if( a ) 
    {
        System.out.println("A"); /* Line 5 */
    } 
    else if(a && b) /* Line 7 */
    { 
        System.out.println( "A && B"); 
    } 
    else /* Line 11 */
    { 
        if ( !b ) 
        {
            System.out.println( "notB") ;
        } 
        else 
        {
            System.out.println( "ELSE" ) ; 
        } 
    } 
}
If a is true and b is true then the output is "A && B"
If a is true and b is false then the output is "notB"
If a is false and b is true then the output is "ELSE"
If a is false and b is false then the output is "ELSE"
Answer: Option
Explanation:

Option C is correct. The output is "ELSE". Only when a is false do the output lines after 11 get some chance of executing.

Option A is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed. The condition at line 7 will never be evaluated (when a is true it will always be trapped by the line 12 condition) therefore the output will never be "A && B".

Option B is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed.

Option D is wrong. The output is "notB".

Discussion:
19 comments Page 2 of 2.

Angelo said:   10 years ago
The "else" statement on line 11 does not seem to refer to any "if".

How is that code correct?

Nagaraj said:   9 years ago
How do you know a=false and b= true?

Default value boolean is 'false' for both a and b.

Aarti gupta said:   10 years ago
What "If (a)" will compares to? Whether it will compare to false or true?

Priyanka said:   1 decade ago
Nice mind boggling question..... !! i took half an hour to solve it....

Aakash said:   1 decade ago
Can anybody tell me why the condition in A will be trapped in line 12.

Sri said:   9 years ago
How to know the default value of b is true?
(2)

Ram said:   1 decade ago
Need more questions like this.

Srikanth Reddy said:   1 decade ago
Good question. !it is amazing.

Umer Hurrah said:   1 decade ago
Please explain your answer?


Post your comments here:

Your comments will be displayed after verification.