Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - Finding the output (Q.No. 5)
5.
What will be the output of the program?
public class If2 
{
    static boolean b1, b2;
    public static void main(String [] args) 
    {
        int x = 0;
        if ( !b1 ) /* Line 7 */
        {
            if ( !b2 ) /* Line 9 */
            {
                b1 = true;
                x++;
                if ( 5 > 6 ) 
                {
                    x++;
                }
                if ( !b1 ) 
                    x = x + 10;
                else if ( b2 = true ) /* Line 19 */
                    x = x + 100;
                else if ( b1 | b2 ) /* Line 21 */
                    x = x + 1000;
            }
        }
        System.out.println(x);
    }
}
0
1
101
111
Answer: Option
Explanation:

As instance variables, b1 and b2 are initialized to false. The if tests on lines 7 and 9 are successful so b1 is set to true and x is incremented. The next if test to succeed is on line 19 (note that the code is not testing to see if b2 is true, it is setting b2 to be true). Since line 19 was successful, subsequent else-if's (line 21) will be skipped.

Discussion:
24 comments Page 3 of 3.

Arun said:   9 years ago
In this statement, if(b2=true) first assign b2 value as true then check condition.

Rani said:   7 years ago
Why not 1001? please explain it.
(1)

Harshad said:   4 years ago
Consider both if ( !b1 ) /* Line 7 */ if ( !b2 ) /* Line 9 */ are true.

Then b1 = true; gets executed //line11
And x++ makes x = 1 //initially x was 0;

alright 5 > 6 is false that's not going to execute anywhere,
Control will come at line no 17...if ( !b1 ) not b1 means false we have already consider b1 is true
then b1 not going to execute.

Yes, else if ( b2 = true ) bcoz we already consider b2 is true x = x + 100; gets executed 101
if one else if executed then control will not transfer to the 2nd else if.
That's why 101 gets printed!.
(1)

Juaneco said:   3 years ago
Here b2 takes the true value.
if ( b2 = true ).

Here it is checked if b2 is true.
if ( b2 == true ).
(1)


Post your comments here:

Your comments will be displayed after verification.