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 2 of 3.

Yash maheshwari said:   10 years ago
Can any one explain it step by step?

Udesha said:   10 years ago
What is the meaning of "if (!b1)"? What does it do?

Don't we have to use a condition inside those parentheses of the if condition?

Raman said:   1 decade ago
If (!b2) //If I change b2 to b1 then why execute this loop? Please

x = x+10;

else if (b1 = true) /*Line 19*/.

x = x + 100;
else if (b1 | b2) /*Line 21*/
x = x + 1000;

Pandu said:   1 decade ago
Can we assign a value to a variable in if condition that mean if (x=5). Is it applicable or not?

Boopathi said:   1 decade ago
Why not consider this part? Please explain.

if(5>6)
{
x++;
}
if(!b)
{
x=x+10;
}

Kunal said:   1 decade ago
Note the difference between b2= true and b==true. The first one assigns b2 to be true and evaluates as true, the second one compares b2 with true.

As the condition is true@ if(b2=true) it will executes the statement x=x+100; and skip the next statement.

Vien said:   1 decade ago
Why? x must be 1001, why 101?

Sunil said:   1 decade ago
How come b2 become true ?

Rakesh said:   1 decade ago
|| is called as short circuit OR operator, it will check its 2nd operand only if the first operand is false and if the first operand is true then it will not care about whether 2nd operand is true or false.

| is simple OR operator it will check its both the operands always.

Rakesh Kumar said:   1 decade ago
How it became possible for this code to run.

Because there must be an else statement after if{} else if{}.

Please some one do reply if I am wrong.


Post your comments here:

Your comments will be displayed after verification.