Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Finding the output (Q.No. 7)
7.
What will be the output of the program?
class Test 
{
    public static void main(String [] args) 
    {
        int x= 0;
        int y= 0;
        for (int z = 0; z < 5; z++) 
        {
            if (( ++x > 2 ) && (++y > 2)) 
            {
                x++;
            }
        }
        System.out.println(x + " " + y);
    }
}
5 2
5 3
6 3
6 4
Answer: Option
Explanation:

In the first two iterations x is incremented once and y is not because of the short circuit && operator. In the third and forth iterations x and y are each incremented, and in the fifth iteration x is doubly incremented and y is incremented.

Discussion:
30 comments Page 2 of 3.

Vinoth said:   1 decade ago
I'm still confusing because "if" condition is failed then the x would not be incremented, It would come out from the loop. Explain me please?

Niharika patidar said:   6 years ago
Please explain to me.

What is the reason that ++y is not executed for the first two times?
(1)

Sushaja said:   3 years ago
@Arnold.

Thank you for explaining the short circuit operator's operation in detail.

Unknown said:   6 years ago
output of int z=2; while(z<20) if((z++)%2==0) system.out.println(z);

Peacz said:   10 years ago
@Uma you can see @Narayana Murthy explain.

He explain so clear.

Magesh said:   2 decades ago
Can any one please mention what is short circuit operator?

Aashish said:   9 years ago
Thanks for your explanation @Arnold Villasanta.

Sunny deol said:   9 years ago
Now I understand this, thank you @Nataliia.

Preethi said:   7 years ago
Thank you good explanation @G.Vivekananda.

Aparna said:   7 years ago
Hi, Please explain this problem using OR.


Post your comments here:

Your comments will be displayed after verification.