Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Finding the output (Q.No. 14)
14.
What will be the output of the program?
class BoolArray 
{
    boolean [] b = new boolean[3];
    int count = 0;

    void set(boolean [] x, int i) 
    {
        x[i] = true;
        ++count;
    }

    public static void main(String [] args) 
    {
        BoolArray ba = new BoolArray();
        ba.set(ba.b, 0);
        ba.set(ba.b, 2);
        ba.test();
    }

    void test() 
    {
        if ( b[0] && b[1] | b[2] )
            count++;
        if ( b[1] && b[(++count - 2)] )
            count += 7;
        System.out.println("count = " + count);
    }
}
count = 0
count = 2
count = 3
count = 4
Answer: Option
Explanation:

The reference variables b and x both refer to the same boolean array. count is incremented for each call to the set() method, and once again when the first if test is true. Because of the && short circuit operator, count is not incremented during the second if test.

Discussion:
31 comments Page 3 of 4.

Gopi said:   1 decade ago
But why it is incremented only in first if in test method ?

Vishumunjal said:   1 decade ago
Why only the first statement is true not second ?

Preethi said:   7 years ago
Thank you for the clear explanation @Jndsln.

Swagatika said:   9 years ago
Please anyone explain the compleat program.

Sainath said:   8 years ago
You are absolutely right Thanks, @Jndlsnl.

Anant said:   7 years ago
I am not getting it. Can anyone help me?

Ravindra singh said:   9 years ago
Nice, got it clearly. Thanks.

Sanju said:   1 decade ago
Please explain whole program.

Javeed said:   1 decade ago
I didn't understand.

Ashi said:   1 decade ago
b[1]=false..how??


Post your comments here:

Your comments will be displayed after verification.