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.

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

Rishi said:   9 years ago
All the static and non static variables retain its value until the program is terminated it doesn't matter whether it is local or global.

I think you got it @Siri.

Siri said:   10 years ago
Count must be 1 because count is not a static declare. Count will be increment to 2 but after end of the block the value will back to 0. If it is static then only count is 3. Correct me if I am wrong.

Huy said:   10 years ago
ba.set(ba.b, 0); // b[0] = true, count = 1.
ba.set(ba.b, 2); // b[2] = true, count = 2.

First if fails since b[1] is false,

Second if fails for same reason, but while evaluating, ++count increases it to 3.

Theoretically, it shouldn't because the program uses lazy approach and would not evaluate the rest of the if statement at all since it fails at the start and it is a && case, or so I read it somewhere.

Sanju said:   1 decade ago
Please explain whole program.

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);

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.

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

RAHUL SRIVASTAVA said:   1 decade ago
The answer is wrong because the count is instance variable so in each block it will take the memory in local stack and destroy after the compilation of the function. Answer will be 1 and to make it 3 count should be static.

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


Post your comments here:

Your comments will be displayed after verification.