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

Pravin said:   1 decade ago
if (b[0] && b[1] | b[2])
count++;
if (b[1] && b[(++count - 2)])
count += 7;
System.out.println("count = " + count);

Parth Soni said:   8 years ago
Can anyone explain how b and x refer to the same array because x's scope is in set method only and it will not update the array b right ?

Jigar said:   1 decade ago
Two set() method incremented count,
Now when test() called,
1st condition is true,
Hence, count is incremented! (post incremented).

Gourav Soni said:   1 decade ago
@[jndlsnl@gmail.com] :
in second if condition we have used ++count...which should increase count by 1 ...so count shud be 4 ..ryt??

Suresh said:   1 decade ago
@Rahul.

Answer is correct because instance variables are stored in heap.not in stack.stack will have only local variables.

Varsha said:   1 decade ago
@gourav : evn i had the same doubt but after reading shipras explanation i am convinced and my doubt is resolved.....

Biswa said:   1 decade ago
Initially count is zero. The set method is call two times, so it 2. How we get 3 please explain.

Samir said:   1 decade ago
When test method call at that time count is increment at one more time.

Bittu said:   8 years ago
Yes, @Jndlsnl.

You are right. Thanks a lot for writing down if values.

Thanvir513@yahoo.com said:   1 decade ago
Why b[0]=true, b[1]=false and b[2]=true ? please explain clearly.


Post your comments here:

Your comments will be displayed after verification.